将行转换为列并按键转换

时间:2014-08-13 05:44:53

标签: sql-server sql-server-2000

我有一张如下表:

foo_table

enter image description here

我想要存档的是:

[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

enter image description here

如何按[部门名称]对它们进行分组?

2 个答案:

答案 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;