編輯:簡化僅使用ANSWER1:
DECLARE @tbl TABLE(id INT,user_id INT,question_id INT,answer1 VARCHAR(1),answer2 VARCHAR(1));
INSERT INTO @tbl VALUES
(1,1,1,'a','x')
,(2,1,2,'c','y')
,(3,1,3,'a','y')
,(4,2,1,'c','y')
,(5,2,2,'a','x');
WITH AllAnswers AS
(
SELECT p.*
FROM
(
SELECT tbl.user_id
,'q' + CAST(tbl.question_id AS VARCHAR(10)) AS columnName
,answer1
FROM @tbl AS tbl
) AS x
PIVOT
(
MIN(answer1) FOR columnName IN(q1,q2,q3 /*Add your question numbers here*/)
) AS p
)
SELECT aa.user_id
,aa.q1
,aa.q2
,aa.q3
/*Get only the questions you want*/
FROM AllAnswers AS aa
/* Result
user_id q1 q2 q3
1 a c a
2 c a NULL
*/
難道這是你的解決方案:
只是一個簡短的說明:當你爲每個問題寫兩個答案時,我把第二個答案放到測試集中。爲了讓一個PIVOT具有多個列,我使用這個技巧將兩個答案連接爲一個僞XML。這是通過其內部索引再次旋轉和拆分的。
結果是所有用戶的列表,其中包含所有問題的答案。使用最後一個SELECT,您可以選擇要提取的問題/答案。
DECLARE @tbl TABLE(id INT,user_id INT,question_id INT,answer1 VARCHAR(1),answer2 VARCHAR(1));
INSERT INTO @tbl VALUES
(1,1,1,'a','x')
,(2,1,2,'c','y')
,(3,1,3,'a','y')
,(4,2,1,'c','y')
,(5,2,2,'a','x');
WITH AllAnswers AS
(
SELECT p.user_id
,CAST(p.q1 AS XML).value('x[1]','varchar(1)') AS q1_1
,CAST(p.q1 AS XML).value('x[2]','varchar(1)') AS q1_2
,CAST(p.q2 AS XML).value('x[1]','varchar(1)') AS q2_1
,CAST(p.q2 AS XML).value('x[2]','varchar(1)') AS q2_2
,CAST(p.q3 AS XML).value('x[1]','varchar(1)') AS q3_1
,CAST(p.q3 AS XML).value('x[2]','varchar(1)') AS q3_2
/*Add all your question numbers here*/
FROM
(
SELECT tbl.user_id
,'q' + CAST(tbl.question_id AS VARCHAR(10)) AS columnName
,'<x>' + ISNULL(answer1,'') + '</x><x>' + ISNULL(answer2,'') + '</x>' AS BothAnswers
FROM @tbl AS tbl
) AS x
PIVOT
(
MIN(BothAnswers) FOR columnName IN(q1,q2,q3 /*Add your question numbers here*/)
) AS p
)
SELECT aa.user_id
,aa.q1_1
,aa.q1_2
,aa.q2_1
,aa.q2_2
,aa.q3_1
,aa.q3_2
/*Get only the questions you want*/
FROM AllAnswers AS aa
在這種情況下,您必須編寫Dynamic Sql,即使用數組列表生成查詢,然後執行它。在sql server中你可以通過EXEC運行動態查詢(「Select ...」) – SeeTheC
你的示例數據和輸出不匹配,這是故意的嗎? 此外,標記您的DBMS請求。 – DarkKnight
您正在使用哪些DBMS? Postgres的?甲骨文? –