【问题标题】:Sum a column of a table based on another sum of a table根据表的另一个总和对表的一列求和
【发布时间】:2012-07-23 18:04:54
【问题描述】:

我有这个代码:

declare @ReportLines table 
    (RebateInvoiceID int, 
     RebateSetupID int ,
     ShortItemNo float primary key(RebateInvoiceID,RebateSetupID,ShortItemNo),
     TotalAmount float,
     InvoiceTotal float,
     TotalQuantity int )
insert @ReportLines
select
  i.RebateInvoiceID
, coalesce(rs.WholesalerRebateSetupID,r.RebateSetupID)
, bl.ShortItemNo
, sum(round(r.Amount,2)) as TotalAmount
, sum(round(TotalAmount,2)) as InvoiceTotal
, sum(r.Quantity) TotalQuantity
from
  @Invoices i
  join RebateInvoices ri (nolock) on 
    ri.RebateInvoiceID=i.RebateInvoiceID
  inner loop join Rebates r (nolock) on
    r.RebateInvoiceID=i.RebateInvoiceID       
  join RebateSetup rs (nolock) on
    rs.RebateSetupID=r.RebateSetupID
  join BidLines bl (nolock) on 
    r.BidLineGuid=bl.BidLineGuid
  join @Products p on
    p.ShortItemNo=bl.ShortItemNo
  left join ChargebackDetailHistory cd (nolock) on 
    r.DocumentBranchPlant = cd.DocumentBranchPlant
    and r.DocumentNumber = cd.DocumentNumber
    and r.DocumentType = cd.DocumentType
    and r.LineNumber = cd.LineNumber
  left join EDI.dbo.JDE_SaleDetail sd (nolock) on 
    r.DocumentBranchPlant = sd.BranchPlant
    and r.DocumentNumber = sd.OrderNumber
    and r.DocumentType = sd.OrderType
    and r.LineNumber = sd.LineNumber

where 
    cd.InvoiceDate between @BeginDate and @EndDate
    or sd.InvoiceDate between @BeginDate and @EndDate
group by
  i.RebateInvoiceID
, coalesce(rs.WholesalerRebateSetupID,r.RebateSetupID)
, bl.ShortItemNo

我想将总金额列中的发票总金额列相加。当我运行上面的查询时,我得到了一堆奇怪的总数。每行的发票总额应该是一个数字,并且与 rebateinvoiceid 一致,因为那是它的分组依据,对吗?

【问题讨论】:

    标签: sql sum


    【解决方案1】:

    您可以进行另一个 Nesty 查询... 像这样:

    insert @ReportLines
    select
       RebateInvoiceID
       , ID
       , ShortItemNo
       , TotalAmount
       , sum(round(TotalAmount,2)) as InvoiceTotal
       , TotalQuantity
    from
    ( 
       select
       i.RebateInvoiceID
       , coalesce(rs.WholesalerRebateSetupID,r.RebateSetupID) as ID
       , bl.ShortItemNo
       , sum(round(r.Amount,2)) as TotalAmount
       , sum(r.Quantity) TotalQuantity
      from (... <the rest of your code here> ...) 
    ) As MyTable
    group by
     RebateInvoiceID, ID, ShortItemNo, TotalAmount, TotalQuantity
    

    【讨论】:

    • 我不是必须以某种方式加入吗?
    • 您能否详细说明该查询?我仍然有问题。
    • 当然,也许您需要为父查询添加一个别名(我的或首先您想查看的任何内容)(我已经编辑了我的帖子)。这个想法是使用您的查询作为子查询进行查询,因为它是一个表,因此您可以从查询中已有的字段中进行选择。如果你想完成所有查询告诉我,我认为你只需要在上面写着...&lt;the rest of your code here&gt;... 的地方完成你的查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多