我有一张如下表:
foo_table
我想要存档的是:
[DepartmentName] , [4] , [5] , [6]
以下是我的尝试:
select DepartmentName,
CASE foo_table.keyid WHEN '4' THEN foo_table.Score END AS [4],
CASE foo_table.keyid WHEN '5' THEN foo_table.Score END AS [5],
CASE foo_table.keyid WHEN '6' THEN foo_table.Score END AS [6]
from foo_table
如何按[部门名称]对它们进行分组?
答案 0 :(得分:1)
select DepartmentName,
max(CASE foo_table.keyid WHEN '4' THEN foo_table.Score END) AS [4],
max(CASE foo_table.keyid WHEN '5' THEN foo_table.Score END) AS [5],
max(CASE foo_table.keyid WHEN '6' THEN foo_table.Score END) AS [6]
from foo_table
group by DepartmentName;
答案 1 :(得分:1)
您必须使用Max
功能
SELECT DepartmentName,
MAX(CASE foo_table.keyid WHEN '4' THEN foo_table.Score END) AS [4],
MAX(CASE foo_table.keyid WHEN '5' THEN foo_table.Score END) AS [5],
MAX(CASE foo_table.keyid WHEN '6' THEN foo_table.Score END) AS [6]
FROM foo_table
GROUP BY DepartmentName;
但我建议你使用 PIVOT
而不是上面。
尝试这样
SELECT DepartmentName,keyid,Score
FROM foo_table X
PIVOT
(
MAX(Score) FOR keyid IN ([4],[5],[6])
) P;