SQL选择来自同一列的多个计数

时间:2017-09-29 13:27:06

标签: sql database select count

我在SQL中有一个表,其中包含以下列:Status,CreateDateTime和Case Type

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 个答案:

答案 0 :(得分: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