如何在列中使用可变数据PIVOT表

时间:2018-03-30 20:34:40

标签: sql sql-server tsql pivot pivot-without-aggregate

所有

rownum  respnum   q2        q3
-----------------------------------
1       33        Missy     155-4
2       46        Melissa   55-98
3       73        Emma      998-4

你如何将上表显示下面的结果?请记住,原始列标题是静态的(q2,q3,...),但答案可能会有所不同。

 rownum respnum   question  answer
-----------------------------------
1       33        q2        Missy
1       33        q3        155-4
2       46        q2        Melissa 
2       46        q3        55-98
3       73        q2        Emmat
3       73        q3        998-4

由于

2 个答案:

答案 0 :(得分:3)

UnPivot 会更高效,但如果您不想指定所有字段,请考虑以下事项:

示例

Select rownum
      ,respnum
      ,C.*
 From YourTable A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
                Select question = a.value('local-name(.)','varchar(100)')
                      ,answer   = a.value('.','varchar(max)') 
                 From  B.XMLData.nodes('/row')  as C1(n)
                 Cross Apply C1.n.nodes('./@*') as C2(a)
                 Where a.value('local-name(.)','varchar(100)') not in ('rownum','respnum')
             ) C

<强>返回

rownum  respnum question    answer
1       33      q2          Missy
1       33      q3          155-4
2       46      q2          Melissa
2       46      q3          55-98
3       73      q2          Emma
3       73      q3          998-4

答案 1 :(得分:1)

使用 UNPIVOT ,我们可以这样做:

select * from 
(select 
    rownum, 
    respnum, 
    Q2=Cast(q2 as varchar(max)),
    Q3=cast(Q3 as varchar (max)) 
 from sample)src
unpivot
( answer for question in ([q2],[q3]))up

see working demo