2017-08-09 61 views
1

我想弄清楚一個直接的數值。SQL數據透視行到沒有聚合的列

我需要將行轉換爲列,員工有不同的問題存儲在行中,我想每個員工最多顯示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

檢查這裏的格式怎麼這麼表。 https://meta.stackexchange.com/questions/96125/how-to-format-sql-tables-in-a-stack-overflow-post –

+0

有趣...這個問題被標記爲SQL Server,雖然問題似乎爲HTML?如果你真的有一個SQL Server的問題,你會想發佈一些t-sql顯示你試圖去的地方,然後有人可以引導你。 – Eli

+0

@Eli問題是OP不知道如何以ascii格式格式化表格並使用HTML,但SO沒有使用html格式 –

回答

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          | 
+-------+------------------------------------------+------------------------------------------+------------------------------------------+ 
+0

您只需要包含3個問題,但是重要的OP解釋了選擇這3個邏輯的用法。 –