将列值拆分为行并为每个id创建唯一记录

时间:2018-01-25 07:12:40

标签: sql-server

我的表就像:

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                         

1 个答案:

答案 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;