SQL将行转移到没有聚合的列

时间:2017-08-09 19:03:49

标签: sql-server

我试图找出一个直接值的支点。

我需要将行转换为列,Employee有不同的问题存储在行中,我想针对每个员工显示最多3个问题  我见过的大多数例子都包括一些聚合。我期待一个直接价值的支点。 来源表

EMPId   Question
 121    Should I refer for a desk assessment
 121    They have accused me of bullying
 121    what services can they be referred for ?
 121    what services can they be referred for ?
 122    They have accused me of bullying
 122    what services can they be referred for ?
 123    what services can they be referred for ?

期望输出

+----------+------------------------------------------+------------------------------------------+------------------------------------------+
|  EMPId   |                Question1                 |                Question2                 |                Question3                 |
+----------+------------------------------------------+------------------------------------------+------------------------------------------+
|      121 | Should I refer for a desk assessment     | They have accused me of bullying         | what services can they be referred for ? |
|      122 | They have accused me of bullying         | what services can they be referred for ? |                                          |
|      123 | what services can they be referred for ? |                                          |                                          |
+----------+------------------------------------------+------------------------------------------+------------------------------------------+

1 个答案:

答案 0 :(得分:0)

您是否正在查看以下查询:

Select * from (
    Select *, RowN = Concat('Question', dense_rank() over(partition by EmpId order by Question) )
        from #questions
) a
pivot (max(Question) for RowN in ([Question1],[Question2],[Question3])) p

如果您的输入是xml,并且您希望翻译的xml,则此查询将无效。

输出如下:

+-------+------------------------------------------+------------------------------------------+------------------------------------------+
| Empid |                Question1                 |                Question2                 |                Question3                 |
+-------+------------------------------------------+------------------------------------------+------------------------------------------+
|   121 | Should I refer for a desk assessment     | They have accused me of bullying         | what services can they be referred for ? |
|   122 | They have accused me of bullying         | what services can they be referred for ? | NULL                                     |
|   123 | what services can they be referred for ? | NULL                                     | NULL                                     |
+-------+------------------------------------------+------------------------------------------+------------------------------------------+