在unpivot

时间:2017-03-07 07:51:26

标签: sql sql-server unpivot

我一直在寻找这个问题的解决方案很长一段时间。但是,无法找到任何。

我有一张表格如下:

Month   Col_1   Col_2   Col_3   Col_4   Col_5   
---------------------------------------------
Jan     NULL    NULL    1       1       1   

我想将此表格取消,以便与字段名(Col_1,Col2等)上的另一个表连接。

我的查询:

select Month,Name,value from 
TableName
    unpivot
    (
        Value 
        for Name in (Col_1,Col_2,Col_3,Col_4,Col_5)  
    ) u 

当前结果:

这使我没有NULL值,如下所示:

Month    Name    Value
-----------------------
Jan      Col_3   1
Jan      Col_4   1
Jan      Col_5   1

预期结果:

我希望NULL包含在结果中。

Month    Name    Value
-----------------------
Jan      Col_1   NULL
Jan      Col_2   NULL
Jan      Col_3   1
Jan      Col_4   1
Jan      Col_5   1

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

<强>查询:

select c.column_name,value
from INFORMATION_SCHEMA.COLUMNS c
left join(select * from 'tablename') t1
unpivot(value for column_name in (col_1,col_2,col_3,col_4,col_5)) t2
on t2.column_name=c.COLUMN_NAME where c.TABLE_NAME='tablename'

Check Snapshot

答案 1 :(得分:0)

SELECT name,value
FROM #Table1
CROSS APPLY (VALUES ('Col_1', Col_1),
                    ('Col_2', Col_2),
                    ('Col_3', Col_3),
                    ('Col_4', Col_4),
                    ('Col_5', Col_5)) 
            CrossApplied (name, value)

输出

name    value
Col_1   NULL
Col_2   NULL
Col_3   1
Col_4   1
Col_5   1

答案 2 :(得分:0)

如果Col_1, Col_2, ...保证不采取特定值,您可以使用以下查询作为解决方法,例如-1

select [Month], Name, NULLIF(value, -1) AS value 
from (
   select [Month],
          coalesce(Col_1, -1) AS Col_1,
          coalesce(Col_2, -1) AS Col_2,
          coalesce(Col_3, -1) AS Col_3,
          coalesce(Col_4, -1) AS Col_4,
          coalesce(Col_5, -1) AS Col_5
   from TableName) AS t
unpivot
(
    Value 
    for Name in (Col_1,Col_2,Col_3,Col_4,Col_5)
) AS u 

Demo here