交叉申请与UNPIVOT

时间:2014-05-12 03:17:27

标签: sql sql-server unpivot cross-apply

我发现UNPIVOT能够自动排除具有NULL值的字段。但是,CROSS APPLY-VALUES方法无法做到这一点。有谁知道如何自动从CROSS APPLY-VALUES中排除NULL值字段?假设,如果它们包含NULL值,则排除字段Field3和Field4。

SELECT 
    E.FieldA, 
    E.FieldB, 
    E.FieldC, 
    DBParam.Display, 
    DBParam.Value
INTO DBParam
FROM
Map_Data AS E
CROSS APPLY (VALUES (Field1, 'Field1'),
            (Field2, 'Field2'), 
            (Field3, 'Field3'),
            (Field4, 'Field4')
) AS DBParam(Value, Display)

1 个答案:

答案 0 :(得分:8)

不使用VALUES,而是使用SELECT

SELECT E.FieldA, E.FieldB, E.FieldC, 
       DBParam.Display, DBParam.Value
INTO DBParam
FROM Map_Data E CROSS APPLY
     (SELECT Value, Display
      FROM (SELECT Field1 as Value, 'Field1' as Display UNION ALL
            SELECT Field2, 'Field2' UNION ALL
            SELECT Field3, 'Field3' UNION ALL
            SELECT Field4, 'Field4'
           ) vd
      WHERE Value is not null
     ) as DBParam(Value, Display);