以下数据结构所需的枢轴

时间:2019-03-06 05:35:00

标签: sql sql-server sql-server-2012 sql-server-2017

我的数据格式如下。

ID   question    answer
1    who         A
1    where       B
1    when        C
1    how         D

我需要的输出如下

id   who   where   when   how
1    A     B       C      D

3 个答案:

答案 0 :(得分:0)

使用条件聚合

  select id, 
  max(case when question='who' then answer end) as "who",
  max(case when question='where' then answer end) as "where",
  max(case when question='when' then answer end) as "when",
  max(case when question='how' then answer end) as "how"
   from table_name
  group by id

答案 1 :(得分:0)

您可以使用动态数据透视查询进行尝试。

create table #temp (ID int, question varchar(20), answer char(1))
insert into #temp values
(1,    'who',         'A'),
(1,    'where',       'B'),
(1,    'when',        'C'),
(1,    'how',         'D')

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question) 
            FROM #temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Id, ' + @cols + ' from 
            (
                select Id
                    ,question
                    , answer
                from #temp
           ) x
            pivot 
            (
                 max(answer)
                for question in (' + @cols + ')
            ) p '


execute(@query)

Live Demo

答案 2 :(得分:0)

您可以尝试这个。

    DECLARE @column AS VARCHAR(MAX), @query  AS VARCHAR(MAX);

    SET @column = STUFF((SELECT distinct ',' + QUOTENAME(t.question) FROM table t FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')

    set @query = 'SELECT Id, ' + @column + ' from 
                (
                    select Id, question, answer from table
                ) x
                pivot 
                ( max(answer) for question in (' + @column + ')
                ) p '


    exec (@query)