在 unpivot 中包含 NULL 值
Include NULL values in unpivot
我一直在寻找这个问题的解决方案很长时间了。但是,找不到。
我有一个 table 如下:
Month Col_1 Col_2 Col_3 Col_4 Col_5
---------------------------------------------
Jan NULL NULL 1 1 1
我想反转这个 table 以便在字段名(Col_1、Col2 等)上与另一个 table 连接。
我的查询:
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
如有任何帮助,我们将不胜感激。
查询:
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'
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
您可以使用以下查询作为解决方法,以防 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
我一直在寻找这个问题的解决方案很长时间了。但是,找不到。
我有一个 table 如下:
Month Col_1 Col_2 Col_3 Col_4 Col_5
---------------------------------------------
Jan NULL NULL 1 1 1
我想反转这个 table 以便在字段名(Col_1、Col2 等)上与另一个 table 连接。
我的查询:
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
如有任何帮助,我们将不胜感激。
查询:
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'
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
您可以使用以下查询作为解决方法,以防 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