如何获得具有连接的列的总和?

时间:2016-08-15 11:23:52

标签: sql sql-server

我正在尝试从此查询中获取包的总和,但它没有给我正确的结果。

Select sum(i.cdin_volumewt)
from cdindex i,Performainv p 
where(cdin_deleted Is null  and p.pinv_deleted is null 
     and (p.pinv_InvoiceProperty ='01' or p.pinv_InvoiceProperty is null ) 
     and (p.pinv_Status in('Draft','Posted') or p.pinv_status is null) )
     and i.cdin_startunstufdate between '2016-07-01'  and '2016-07-11'
group by i.cdin_cdindexid

这是查询结果的屏幕截图:

ScreenShot of the result

预期结果记录在一起,列记录的总累计总和。

1 个答案:

答案 0 :(得分:0)

您正在使用GROUP BY,因此您可以获得多个行i.cdin_cdindexid。你可以摆脱GROUP BY:

Select sum(i.cdin_volumewt)
from cdindex i
inner join Performainv p 
     on i.[SOME ID] = p.[SOME ID]
where(cdin_deleted Is null  and p.pinv_deleted is null 
     and (p.pinv_InvoiceProperty ='01' or p.pinv_InvoiceProperty is null ) 
     and (p.pinv_Status in('Draft','Posted') or p.pinv_status is null) )
     and i.cdin_startunstufdate between '2016-07-01'  and '2016-07-11'

或使用子查询:

SELECT SUM(p.cdin_volumewt)
FROM (
     Select sum(i.cdin_volumewt) as cdin_volumewt
     from cdindex i
     inner join Performainv p 
          on i.[SOME ID] = p.[SOME ID]
     where(cdin_deleted Is null  and p.pinv_deleted is null 
          and (p.pinv_InvoiceProperty ='01' or p.pinv_InvoiceProperty is null ) 
          and (p.pinv_Status in('Draft','Posted') or p.pinv_status is null) )
          and i.cdin_startunstufdate between '2016-07-01'  and '2016-07-11'
     group by i.cdin_cdindexid
) as p