来自同一个表的两个sql查询的求和结果

时间:2015-10-29 16:22:33

标签: sql sql-server-2008 ssrs-2008-r2

我已经提出了这两个查询,根据具体的where子句查找单个表上字段的总和:

Select Sum(dbo.Charges.[TRANS AMT]) as Total1  
from dbo.Charges 
where (dbo.Charges.[TRAN ID] IN (100, 20, 50, 52, 55, 60, 600))   

Select Sum(dbo.Charges.[TRANS AMT]) as Total2  
from dbo.Charges 
where dbo.Charges.[TRAN ID] = 200

我无法找到将两个查询的结果相加以获得总计的方法。有关如何做到这一点的任何建议吗?

2 个答案:

答案 0 :(得分:2)

只需将[TRAN ID] 200添加到IN子句:

SELECT SUM(dbo.Charges.[TRANS AMT]) AS GRAND_TOTAL
FROM dbo.Charges 
WHERE dbo.Charges.[TRAN ID] IN (100, 20, 50, 52, 55, 60, 600, 200);

获得所有金额:

SELECT
   SUM(CASE WHEN dbo.Charges.[TRANS AMT] <> 200 THEN dbo.Charges.[TRANS AMT] END) AS Total1,
   SUM(CASE WHEN dbo.Charges.[TRANS AMT] = 200 THEN dbo.Charges.[TRANS AMT] END) AS Total2,
   SUM(dbo.Charges.[TRANS AMT]) AS GRAND_TOTAL
FROM dbo.Charges 
WHERE dbo.Charges.[TRAN ID] IN (100, 20, 50, 52, 55, 60, 600, 200);

答案 1 :(得分:0)

由于产生这些总和的行是互斥的,您可以在[TRAN ID]子句中合并where

SELECT SUM(dbo.Charges.[TRANS AMT]) as GrandTotal
FROM   dbo.Charges
WHERE  dbo.Charges.[TRAN ID] IN (100, 20, 50, 52, 55, 60, 600, 200)