可能重复:
Sum a column of a table based on another sum of a table和函数在SQL不工作
我从一个子选择在SQL中已经总结出列总结出列,但它给了我同样的作为已加总列的值。 TotalAmount应该合计为InvoiceTotal,但它只是复制相同的值。任何人都可以看到我做错了什么,或者如果有更好的方式去做这件事?
declare @ReportLines table
(RebateInvoiceID int,
RebateSetupID int ,
ShortItemNo float primary key(RebateInvoiceID,RebateSetupID,ShortItemNo),
TotalAmount float,
InvoiceTotal float,
TotalQuantity int)
insert @ReportLines
select
Total.RebateInvoiceID
, Total.ID
, Total.ShortItemNo
, Total.TotalAmount
, sum(Total.TotalAmount) as InvoiceTotal
, Total.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
@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
) Total
group by
total.rebateinvoiceid,
total.ID,
total.shortitemno,
total.totalamount,
total.totalquantity
如果您没有得到第一个问题的答案,那么请考虑将其编辑为更清楚,而不是发布完全相同的问题 – Taryn 2012-07-23 20:54:54
@user ...尝试在查询结束时从组中删除total.totalamount,然后从选择....看看会发生什么 – MikeTWebb 2012-07-23 20:56:00