使用select作为ID等于行ID的列作为SQL

时间:2019-03-27 22:43:48

标签: sql sql-server tsql

我想查询类似的东西。

SELECT 
    COLUMN_ID, 
    (SELECT COUNT() WHERE ID = the current row COLUMN_ID WHERE status = 1) as column2, 
    (SELECT COUNT() WHERE ID = the current row COLUMN_ID WHERE status = 2) as column 3 

如何根据各行中COLUMN_ID的值动态地将选择计数用作一列

要查询的数据示例:

|      Column id      |       status     |
+---------------------+------------------+
|        0001         |         1        |
|        0001         |         2        |
|        0001         |         1        |
|        0002         |         1        |

样本输出

|      Column id      |     status 1     |     status 2     |
+---------------------+------------------+------------------+
|        0001         |         2        |        1         |
|        0002         |         1        |        0         |

1 个答案:

答案 0 :(得分:2)

您可以将SUM与CASE WHEN子句一起使用

SELECT 
    COLUMN_ID, 
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as column2, 
    SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as column3
FROM TABLE
GROUP BY COLUMN_ID

另一种方法

SELECT DISTINCT
    COLUMN_ID, 
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) OVER(PARTITION BY COLUMN_ID) as column2, 
    SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) OVER(PARTITION BY COLUMN_ID) as column3
FROM TABLE