2012-07-23 5 views
0

가능한 중복 :
Sum a column of a table based on another sum of a tableSUM 함수는 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 
+1

첫 번째 질문에 대한 답변을 얻지 못했다면 정확히 동일한 질문을 게시하는 것이 아니라보다 명확하게 편집하는 것이 좋습니다. – Taryn

+0

@user ... 쿼리의 마지막에 그룹에서 total.totalamount를 제거하고 선택에서 .... 무슨 일이 일어나는가 보자 – MikeTWebb

답변

3

SUM을 수행하려는 동일한 필드에서 그룹화하지 마십시오.

+1

정확히 내가 뭘 잘못했는지! –

1

TotalAmountTotalQuantity으로 그룹화했기 때문입니다. 이 값으로 그룹화하는 것은 의미가 없습니다. 그리고 세 개의 나머지 그룹 필드는 하위 선택에서와 동일하므로 동일한 행을 가져옵니다. 하위 선택의 여러 행을 외부 선택의 한 행으로 통합하여 합계를 얻으려면 더 적은 수의 필드로 그룹화해야합니다.

하지만이 외부 선택이 전혀 의미가없는 것처럼 보입니다. 내부 선택을 혼자 사용하지 않는 이유는 무엇입니까?