我的表就像:
id name question answer comment
1 ann are you happy? yes yes, i am happy.
1 ann got job? no not yet
2 joe are you happy? no sometimes.
2 joe got job? no not yet
3 jim are you happy? yes
3 jim got job? yes not yet
我希望将表转换为:
id name question1 answr1 comment1 question2 answer2 comment2
1 ann are you happy? yes yes,i am happy. got job? no not yet
2 joe are you happy? no sometimes. got job? no not yet
3 jim are you happy? yes got job? yes
答案 0 :(得分:0)
我必须告诉你,你的桌子设计不好吗?这违反了规范化的规则......
最好是修复此
如果您有标准问题,可以为此引入一个自己的表,并将它们链接到n:m
相关的映射表中。
根据您的实际情况,您可以使用条件汇总:
DECLARE @mockupTable TABLE(id INT,name VARCHAR(100),question VARCHAR(100),answer VARCHAR(100),comment VARCHAR(100));
INSERT INTO @mockupTable VALUES
(1,'ann','are you happy?','yes','yes, i am happy.')
,(1,'ann','got job?','no','not yet')
,(2,'joe','are you happy?','no','sometimes.')
,(2,'joe','got job?','no','not yet')
,(3,'jim','are you happy?','yes','')
,(3,'jim','got job?','yes','not yet');
WITH NumberedRows AS
(
SELECT t.*
,ROW_NUMBER() OVER(PARTITION BY id ORDER BY (SELECT NULL)) AS RowNr
FROM @mockupTable AS t
)
SELECT id,name
,MAX(CASE WHEN RowNr = 1 THEN question END) AS question1
,MAX(CASE WHEN RowNr = 1 THEN answer END) AS answer1
,MAX(CASE WHEN RowNr = 1 THEN comment END) AS comment1
,MAX(CASE WHEN RowNr = 2 THEN question END) AS question2
,MAX(CASE WHEN RowNr = 2 THEN answer END) AS answer2
,MAX(CASE WHEN RowNr = 2 THEN comment END) AS comment2
FROM NumberedRows
GROUP BY id,name;