将两个查询合并为一个

时间:2015-10-07 08:24:43

标签: sql sql-server sql-server-2008 select

我有两个不同结果集的查询,但在其中一个查询中只有一个条件是附加的。两个查询都从同一个表中获取。 第一个查询:

SELECT cm.ctm, count_big(*) AS TOTAL
                       FROM dbo_cm.cm
                       WHERE 
                          cm.a= 'abc' AND 
                          cm.b= 1 AND 
                          cm.ps IS NOT NULL AND 
                          datepart(MONTH, cm.ps) = 7 AND 
                          datepart(YEAR, cm.ps) = 2015  
                       GROUP BY cm.ctm

第二个查询:

SELECT cm.ctm, count_big(*) AS TOTAL
                       FROM dbo_cm.cm
                       WHERE 
                          cm.a= 'abc' AND 
                          cm.b= 1 AND 
                          cm.ps IS NOT NULL AND 
                          datepart(MONTH, cm.ps) = 7 AND 
                          datepart(YEAR, cm.ps) = 2015 and
                          cm.as>cm.ps
                       GROUP BY cm.ctm

如何通过将此查询合并为一个来简化此查询?为此,我们在Oracle中使用decode

2 个答案:

答案 0 :(得分:3)

通过将第二个查询中的附加条件移动到case表达式并在不满足条件时返回null,可以将这两个查询合并为一个。与任何聚合函数一样,count_big将忽略null s:

SELECT   cm.ctm, 
         COUNT_BIG(*) AS total1,
         COUNT_BIG(CASE WHEN cm.as > cm.ps THEN 1 ELSE NULL END) AS total2
FROM     dbo_cm.cm
WHERE    cm.a= 'abc' AND 
         cm.b= 1 AND 
         cm.ps IS NOT NULL AND 
         DATEPART(MONTH, cm.ps) = 7 AND 
         DATEPART(YEAR, cm.ps) = 2015 AND
GROUP BY cm.ctm

答案 1 :(得分:1)

您可以使用SUM(CASE...)之类的:

SELECT
   cm.ctm,
   count_big(*) AS TOTAL1,
   SUM(CASE WHEN cm.[as]>cm.[ps] THEN 1 ELSE 0 END) AS TOTAL2
FROM dbo_cm.cm
WHERE cm.a= 'abc'
  AND cm.b= 1 
  AND cm.ps IS NOT NULL
  AND datepart(MONTH, cm.ps) = 7
  AND datepart(YEAR, cm.ps) = 2015  
GROUP BY cm.ctm