我有两列专栏:名字和等级。看起来像这样:
NAME | GRADE Adam | 1 Adam | 2 Adam | 2 Adam | 3 Frank | 2 Frank | 1
现在我想创建一个如下所示的视图:
NAME | GRADE 1 | GRADE 2 | GRADE 3 Adam | 1 | 2 | 1 Frank | 1 | 1 | 0
我写了这个:
SELECT Name, (SELECT COUNT(Grade) FROM dbo.Rodzaj WHERE Grade = '1') as Grade_1, (SELECT COUNT(Grade) FROM dbo.Rodzaj WHERE Grade = '2) as Grade_2, (SELECT COUNT(Grade) FROM dbo.Rodzaj WHERE Grade = '3') as Grade_3 FROM dbo.Rodzaj GROUP BY Name
但它不起作用...... 我将不胜感激任何帮助
答案 0 :(得分:3)
您正在寻找的是一个“数据透视表”,它由一系列CASE
语句完成,每个条件应用1或0,然后SUM()
向上和0检索计数。
SELECT
NAME,
SUM(CASE WHEN GRADE = 1 THEN 1 ELSE 0 END) AS GRADE1,
SUM(CASE WHEN GRADE = 2 THEN 1 ELSE 0 END) AS GRADE2,
SUM(CASE WHEN GRADE = 3 THEN 1 ELSE 0 END) AS GRADE3
FROM Rodzaj
GROUP BY NAME
请注意,如果您需要具有动态数量的列,则必须使用脚本语言和循环来构造查询。 (或存储过程中的循环)