2017-09-29 86 views
1

我有一個表中的SQL有以下欄目:狀態,CreateDateTime和案例類型SQL與多個計數來自同一列中選擇

10行數據的示例如下所示:

Resolved-Withdrawn 2017-08-28 10:20:58.820 Termination Quote DE 
    Pending-Customer 2017-08-28 10:44:37.987 Termination Quote DE 
    Pending-Customer 2017-08-28 10:44:39.953 Termination Quote DE 
    Pending-Customer 2017-08-28 10:51:55.643 Termination Quote DE 
    Pending-Customer 2017-08-28 10:51:56.513 Termination Quote DE 
    Pending-Customer 2017-08-28 10:54:20.160 Termination Quote DE 
    Pending-Customer 2017-08-28 10:54:20.747 Termination Quote DE 
    Pending-Customer 2017-09-10 06:12:52.113 Termination Quote DE 
    Pending-Customer 2017-09-15 12:34:32.657 Termination Quote DE 

我想實現以下目標:

Status    Total_August  Total_September 
    ----------------------------------------------------- 
    Resolved-Withdrawn 1    0 
    Pending-Customer  6    2 

我將如何創建SQL中的這個查詢?

我最初的想法是這樣的(這顯然是行不通的),但也許它可以讓你更好的理解我的思維過程,作爲一個非經驗的用戶。

SELECT Status, COUNT(pxCreateDateTime) as Total_August, COUNT(pxCreateDateTime) as Total_September 
    FROM ContractMgtWork 
    WHERE MONTH(pxCreateDateTime) = 8 and YEAR(pxCreateDateTime) = 2017 AND 
    CaseType = 'Amortization Schedule DE' 
    GROUP BY Status 

回答

1

count,像許多其他聚合函數,跳過null秒。您可以通過計數case表達任何你想利用這個屬性來計算:

SELECT Status, 
     COUNT(CASE WHEN MONTH(pxCreateDateTime) = 8 THEN 1 END) AS Total_August, 
     COUNT(CASE WHEN MONTH(pxCreateDateTime) = 9 THEN 1 END) AS Total_September 
FROM  ContractMgtWork 
WHERE YEAR(pxCreateDateTime) = 2017 AND 
     CaseType = 'Amortization Schedule DE' 
GROUP BY Status 
+0

啊,這也正是我想要的,謝謝:) – R100