2017-08-16 60 views
0

我從查詢發現計數值的總和而我做了類似下面使用多個SUM

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值。那麼,我的查詢正確或使用的計數SUM多個實例在SQL查詢

回答

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; 
+0

我們怎樣才能使一個新的列在此查詢值TOTAL_1-TOTAL_2的區別呢?因爲Total_1,2字段實時生成我猜 –

+0

@JibinMathew。 。 。這不是你原來的問題的一部分。您可以使用子查詢並按名稱減去字段,也可以在它們之間用'-'重複表達式。 –