SQL Server中的摘要查询

时间:2016-01-04 10:27:15

标签: sql-server sql-server-2008 sql-server-2012

我有以下数据

ID                                    Status
5bcb5961-20e-41b7-8af0-87ffe127830c   1
140c7f17-dba5-4bc8-1fb-062d1325c399   5
5bcb5961-20e-41b7-8af0-87ffe127830c   5
5bcb5961-20e-41b7-8af0-87ffe127830c   0

我希望以摘要形式输出。

ID                                     Status_1  Status_5   Status_0
5bcb5961-d20e-41b7-8af0-87ffe127830c   1         1          1
140c7f17-dba5-4bc8-b1fb-062d1325c399   0         1          0 

我可以查询此输出吗?

1 个答案:

答案 0 :(得分:3)

SELECT
      ID
    , Status_1 = COUNT(CASE WHEN [Status] = 1 THEN 1 END)
    , Status_5 = COUNT(CASE WHEN [Status] = 5 THEN 1 END)
    , Status_0 = COUNT(CASE WHEN [Status] = 0 THEN 1 END)
FROM tbl
GROUP BY ID