UNPIVOT不会返回NULL,但我在比较查询中需要它们.我试图避免使用ISNULL以下示例(因为在真正的sql中有超过100个字段:
Select ID, theValue, column_name From (select ID, ISNULL(CAST([TheColumnToCompare] AS VarChar(1000)), '') as TheColumnToCompare from MyView where The_Date = '04/30/2009' ) MA UNPIVOT (theValue FOR column_name IN ([TheColumnToCompare]) ) AS unpvt
任何替代品?
要保留NULL,请使用CROSS JOIN ... CASE:
select a.ID, b.column_name , column_value = case b.column_name when 'col1' then a.col1 when 'col2' then a.col2 when 'col3' then a.col3 when 'col4' then a.col4 end from ( select ID, col1, col2, col3, col4 from table1 ) a cross join ( select 'col1' union all select 'col2' union all select 'col3' union all select 'col4' ) b (column_name)
代替:
select ID, column_name, column_value From ( select ID, col1, col2, col3, col4 from from table1 ) a unpivot ( column_value FOR column_name IN ( col1, col2, col3, col4) ) b
具有列模式的文本编辑器使这些查询更容易编写.UltraEdit拥有它,Emacs也是如此.在Emacs中,它被称为矩形编辑.
您可能需要为100列编写脚本.
这是一个真正的痛苦.你必须在之前将它们切换出来UNPIVOT
,因为没有为行进行生成ISNULL()
- 代码生成是你的朋友.
我也遇到了问题PIVOT
.丢失的行变成了NULL
,ISNULL()
如果缺少的值与0.0
例如相同,则必须在行中一直包裹.
我遇到了同样的问题。使用CROSS APPLY
(SQL Server 2005及更高版本)代替Unpivot
解决了该问题。我根据本文找到了一种解决方案,它是UNPIVOT的替代方法(更好吗?)
,我举了以下示例来说明CROSS APPLY不会忽略NULL Unpivot
。
create table #Orders (OrderDate datetime, product nvarchar(100), ItemsCount float, GrossAmount float, employee nvarchar(100)) insert into #Orders select getutcdate(),'Windows',10,10.32,'Me' union select getutcdate(),'Office',31,21.23,'you' union select getutcdate(),'Office',31,55.45,'me' union select getutcdate(),'Windows',10,null,'You' SELECT OrderDate, product,employee,Measure,MeasureType from #Orders orders CROSS APPLY ( VALUES ('ItemsCount',ItemsCount),('GrossAmount',GrossAmount) ) x(MeasureType, Measure) SELECT OrderDate, product,employee,Measure,MeasureType from #Orders orders UNPIVOT (Measure FOR MeasureType IN (ItemsCount,GrossAmount) )AS unpvt; drop table #Orders