用于计算列条目的SQL语句

时间:2013-02-14 23:25:52

标签: sql pivot

鉴于以下数据,

TEST_SET_1   TEST_1     PASSED

TEST_SET_1   TEST_1     NOT COMPLETED

TEST_SET_1   TEST_1     PASSED

TEST_SET_1   TEST_1     FAILED

TEST_SET_1   TEST_1     FAILED

如何使用SQL格式化它以显示如下?

TEST SET    TEST      PASSED   FAILED   NOT COMPLETED

TEST_SET_1   TEST_1      2         2           1

1 个答案:

答案 0 :(得分:2)

这样的事情:

SELECT
    [TEST SET],
    [TEST],
    SUM(CASE WHEN [state]='PASSED' THEN 1 ELSE 0 END) AS PASSED,
    SUM(CASE WHEN [state]='FAILED' THEN 1 ELSE 0 END) AS FAILED,
    SUM(CASE WHEN [state]='NOT COMPLETED' THEN 1 ELSE 0 END) AS [NOT COMPLETED]
FROM
    table
GROUP BY
    [TEST SET],
    [TEST]

或者,如果您想使用PIVOT并使用MSSQL 2005+。然后你就可以这样做:

SELECT
    *
FROM
(
    SELECT
        [TEST SET],
        [TEST],
        [state],
        1 AS StaticNbr
    FROM
        table
) AS SorceTable
PIVOT
(
    SUM(StaticNbr)
    FOR [state] IN ([PASSED], [FAILED], [NOT COMPLETED])
) AS pvt