将行转换为列

时间:2016-07-20 22:17:55

标签: sql sql-server

我在sql server 2005中有一个表,其中有3列id,问题和答案。

数据如下 -

id  question  answer    
1   married    yes
1   name       John
2   married    No
2   name       Dave
3   married    yes
3   name       Rob

我期待下面的结果 -

ID  married  name
1   yes      John
2   no       Dave
3   yes      Rob

提前致谢

1 个答案:

答案 0 :(得分:2)

Select ID
      ,MAX(CASE WHEN question = 'married' THEN answer END) AS Married
      ,MAX(CASE WHEN question = 'name'    THEN answer END) AS Name
FROM TableName
GROUP BY ID