33

UNPIVOT不会返回NULLs,但我需要它们进行比较query。我试图避免使用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

有什么选择吗?

4

7 回答 7

25

要保留 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 table1
  ) a
unpivot (
  column_value FOR column_name IN (
    col1, col2, col3, col4)
  ) b

具有列模式的文本编辑器使此类查询更易于编写。UltraEdit 有,Emacs 也有。在 Emacs 中,它被称为矩形编辑。

您可能需要为 100 列编写脚本。

于 2009-06-17T04:52:09.820 回答
19

这是一个真正的痛苦。您必须在 之前将它们切换出去UNPIVOT,因为没有生成用于ISNULL()操作的行 - 代码生成是您的朋友。

我也有这个问题PIVOT。缺失的行变成,如果缺失值与例如相同,则NULL必须将其一直包裹在行中。ISNULL()0.0

于 2009-06-16T19:57:53.953 回答
9

我遇到了同样的问题。使用CROSS APPLY(SQL Server 2005 及更高版本)而不是Unpivot解决问题。我根据这篇文章An Alternative (Better?) Method to 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
于 2017-04-27T09:55:06.067 回答
3

或者,在 SQLServer 2008 中以更短的方式:

...
cross join 
(values('col1'), ('col2'), ('col3'), ('col4')) column_names(column_name)
于 2010-10-14T09:55:48.387 回答
2

我发现左外部将 UNPIVOT 结果加入到完整的字段列表中,方便地从 INFORMATION_SCHEMA 中提取,在某些情况下可以实际解决这个问题。

-- test data
CREATE TABLE _t1(name varchar(20),object_id varchar(20),principal_id varchar(20),schema_id varchar(20),parent_object_id varchar(20),type varchar(20),type_desc varchar(20),create_date varchar(20),modify_date varchar(20),is_ms_shipped varchar(20),is_published varchar(20),is_schema_published varchar(20))
INSERT INTO _t1 SELECT 'blah1', 3, NULL, 4, 0, 'blah2', 'blah3', '20100402 16:59:23.267', NULL, 1, 0, 0 

-- example
select c.COLUMN_NAME, Value
from INFORMATION_SCHEMA.COLUMNS c
left join (
  select * from _t1
) q1
unpivot (Value for COLUMN_NAME in (name,object_id,principal_id,schema_id,parent_object_id,type,type_desc,create_date,modify_date,is_ms_shipped,is_published,is_schema_published)
) t on t.COLUMN_NAME = c.COLUMN_NAME
where c.TABLE_NAME = '_t1'
</pre>

输出看起来像:

+----------------------------------+----------+
| COLUMN_NAME | 价值 |
+----------------------------------+----------+
| 姓名 | 废话1 |
| object_id | 3 |
| principal_id | 空 | <======
| schema_id | 4 |
| parent_object_id | 0 |
| 类型 | 废话2 |
| 类型描述 | 废话3 |
| 创建日期 | 20100402 16:59:23.26 |
| 修改日期 | 空 | <======
| is_ms_shipped | 1 |
| is_published | 0 |
| is_schema_published | 0 |
+----------------------------------+----------+
    

于 2012-12-08T02:44:08.630 回答
1

使用动态 SQL 和 COALESCE,我解决了这样的问题:

DECLARE @SQL NVARCHAR(MAX)
DECLARE @cols NVARCHAR(MAX)
DECLARE @dataCols NVARCHAR(MAX)

SELECT 
    @dataCols = COALESCE(@dataCols + ', ' + 'ISNULL(' + Name + ',0) ' + Name , 'ISNULL(' + Name + ',0) ' + Name )
FROM Metric WITH (NOLOCK)
ORDER BY ID

SELECT 
    @cols = COALESCE(@cols + ', ' + Name , Name )
FROM Metric WITH (NOLOCK)
ORDER BY ID

SET @SQL = 'SELECT ArchiveID, MetricDate, BoxID, GroupID, ID MetricID, MetricName, Value
            FROM 
               (SELECT ArchiveID, [Date] MetricDate, BoxID, GroupID,  ' + @dataCols + '
                FROM MetricData WITH (NOLOCK)
                INNER JOIN Archive WITH (NOLOCK)
                    ON ArchiveID = ID
                WHERE BoxID = ' + CONVERT(VARCHAR(40), @BoxID) + '
                AND GroupID = ' + CONVERT(VARCHAR(40), @GroupID) + ') p
            UNPIVOT
               (Value FOR MetricName IN 
                  (' + @cols + ')
            )AS unpvt
            INNER JOIN Metric WITH (NOLOCK)
                ON MetricName  = Name
            ORDER BY MetricID, MetricDate'

EXECUTE( @SQL )
于 2012-01-09T17:30:15.330 回答
-1

ISNULL 是答案的一半。使用 NULLIF 转换回 NULL。例如

DECLARE @temp TABLE(
    Foo varchar(50),
    Bar varchar(50) NULL
    );

INSERT INTO @temp( Foo,Bar )VALUES( 'licious',NULL );

SELECT * FROM @temp;

SELECT 
    Col,
    NULLIF( Val,'0Null' ) AS Val 
FROM(
    SELECT
        Foo,
        ISNULL( Bar,'0Null' ) AS Bar
    FROM
        @temp
    ) AS t
UNPIVOT(
    Val FOR Col IN(
        Foo,
        Bar 
        )
    ) up;

这里我使用“0Null”作为我的中间值。你可以使用任何你喜欢的东西。但是,如果您选择诸如“Null”之类的真实世界的内容,则可能会与用户输入发生冲突。垃圾可以正常工作“!@#34())0”,但可能会让未来的编码人员更加困惑。我相信你明白了。

于 2014-10-10T17:22:58.797 回答