将来自不同行的数据合并到不同的列

时间:2015-10-22 13:35:33

标签: sql

我有一张桌子(T)

User | Language | Value
-----------------------
1    |1         | string
1    |2         | otherString

并希望合并/加入它们以获得此

User | Language_1 | Language_2
--------------------------------
1    |string      | otherString

我试过这样的事情

SELECT       USER,
             (CASE WHEN Language = 1 THEN Value END) AS language_1,
             (CASE WHEN Language = 2 THEN Value END) AS language_2
FROM         T

但是我得到这样的结果(我本来应该这样)

User | Language_1 | Language_2
--------------------------------
1    |string      | NULL
1    |NULL        | otherString

做正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

你只需要一个聚合

SELECT USER,
         MAX(CASE WHEN Language = 1 THEN Value END) AS language_1,
         MAX(CASE WHEN Language = 2 THEN Value END) AS language_2
FROM  T
GROUP BY USER