获得单行结果

时间:2018-01-03 09:13:08

标签: sql group-by

我在下面的桌子上查询。

Table view

SELECT [RiskUniqueIdentificationNo]
    ,Count(*) AS TotalNoOfTasks
    ,[Status]
FROM [dbo].[Tasks]
GROUP BY [RiskUniqueIdentificationNo]
    ,[Status]

这是我的结果集

result set against my group by query

但问题是我希望以下列方式获得每个[RiskUniqueIdentificationNo]的结果

     | RiskUniqueIdentificationNo | | TotalNoOfTasks |  | InProgressTask | | ClosedTask |
     ------------ ------------  ------------ ------------------------- ------------------
     |             1              | |        3       |  |        2       | | 1|

我试图做这样的事情

SELECT [RiskUniqueIdentificationNo]
    ,Count(*) AS TotalNoOfTasks
    ,CASE 
        WHEN [Status] = 'Closed'
            THEN COUNT([Status])
        ELSE 0
        END AS ClosedTasks
    ,CASE 
        WHEN [Status] != 'Closed'
            AND [EndDate] < GETDATE()
            THEN COUNT([Status])
        ELSE 0
        END AS OverdueTasks
FROM [dbo].[Tasks]
GROUP BY [RiskUniqueIdentificationNo]
    ,[Status]

但不能成功。我需要帮助,我该如何实现这一目标。

2 个答案:

答案 0 :(得分:0)

GROUP BY移除状态,并使用COUNT执行CASE

SELECT [RiskUniqueIdentificationNo],
       COUNT(1) AS TotalNoOfTasks,
       COUNT(CASE WHEN [Status]<> 'Closed' THEN 1 END) AS InProgressTask,
       COUNT(CASE WHEN [Status]= 'Closed' THEN 1 END) AS ClosedTask
FROM [dbo].[Tasks]
GROUP BY [RiskUniqueIdentificationNo]

答案 1 :(得分:0)

转到条件聚合,如下所示

Select [RiskUniqueIdentificationNo],
       Count(*) as TotalNoOfTasks, 
       sum(case when [Status] = 'In progress' then 1 else 0 end) [InProgressTask],
       sum(case when [Status] = 'Closed' then 1 else 0 end) [ClosedTask] 
from [dbo].[Tasks]
group by [RiskUniqueIdentificationNo]