在单个查询中使用COUNT的多个SUM

时间:2017-08-16 01:44:43

标签: sql sql-server

我必须从查询中找到计数值的总和,我就像下面那样

SELECT 
    SUM(Total) AS SUMV   
FROM
    (SELECT   
         COUNT(Session.SessionID) AS Total   
     FROM 
         [Session]
     WHERE
         DateCreated >='2016-03-20' 
         AND DateCreated <= '2016-03-22'
     GROUP BY 
         CAST(DateCreated AS DATE)) s 

现在我必须找到具有不同条件的计数总和,我试图将总和值作为上表的第二列,如下所示

SELECT 
    SUM(Total) AS SUMV, SUM(Total2) AS SUMV2  
FROM
    (SELECT   
         COUNT(Session.SessionID) AS Total   
     FROM 
         [Session]
     WHERE 
         DateCreated >='2016-03-20' 
         AND DateCreated <= '2016-03-22'
     GROUP BY  
         CAST(DateCreated AS DATE)) s, 
    (SELECT   
         COUNT(Session.SessionID) AS Total2   
     FROM 
         [Session]
     WHERE
         DateCreated >='2016-03-23' 
         AND DateCreated <= '2016-03-25'
     GROUP BY
         CAST(DateCreated AS DATE)) s2

但是SUM2没有返回正确的SUM值。因此,我的查询是正确的,或者在SQL查询中使用多个SUM计数实例的更好方法

1 个答案:

答案 0 :(得分:1)

您可以将第一个查询编写为:

SELECT COUNT(*)
FROM [Session] s
WHERE DateCreated >= '2016-03-20' AND  DateCreated <= '2016-03-22';

您可以使用条件聚合进行多次求和:

SELECT SUM(CASE WHEN DateCreated >= '2016-03-20' AND  DateCreated <= '2016-03-22'
            THEN 1 ELSE 0
           END) AS Total_1,
       SUM(CASE WHEN DateCreated >= '2016-03-23' AND  DateCreated <= '2016-03-25'
            THEN 1 ELSE 0
           END) AS Total_2           
FROM [Session] s;