SQL Pivot使用count

时间:2016-03-30 04:49:41

标签: sql oracle pivot

我有一张表格,其中包含以下条目

ID | column   | value
------------------------
1  | status   | DONE
2  | status   | FAILED
1  | progress | Green
2  | progress | Red

我希望输出为

ID | DONE | FAILED | GREEN | RED
1  | 1    | 0      | 1     | 0
2  | 0    | 1      | 0     | 1

请让我知道查询。我尝试过枢轴但没有得到结果。

2 个答案:

答案 0 :(得分:1)

这是一个标准的数据透视查询解决方案,它不使用SQL Server内置的PIVOT功能:

SELECT ID,
    SUM(CASE WHEN value = 'DONE' THEN 1 ELSE 0 END)   AS DONE,
    SUM(CASE WHEN value = 'FAILED' THEN 1 ELSE 0 END) AS FAILED,
    SUM(CASE WHEN value = 'Green' THEN 1 ELSE 0 END)  AS GREEN,
    SUM(CASE WHEN value = 'Red' THEN 1 ELSE 0 END)    AS RED
FROM yourTable
GROUP BY ID

答案 1 :(得分:1)

m