SQL Server:如果列不为空,则显示为新行

时间:2018-12-20 16:46:47

标签: sql sql-server

我有一张这样的桌子:

id  name  col1  col2  col3  col4  col5  col6
----------------------------------------------
1   user  b     c     e     f     g     Null

我想像col4那样显示结果,而col5不为空,但不显示col6为空:

id  name  col1  col2  col3  col4  
----------------------------------
1   user  b     c     e     f          
1   user  b     c     e     g(from col5)  

3 个答案:

答案 0 :(得分:1)

您可以为此使用UNPIVOT。这会自动排除NULL

SELECT id,
       name,
       col1,
       col2,
       col3,
       ucol AS col4
FROM   YourTable
       UNPIVOT (x
               FOR ucol IN (col4,
                            col5,
                            col6)) u 

答案 1 :(得分:0)

使用UNION

SELECT id, name, col1, col2, col3, col4 FROM tablename
UNION
SELECT id, name, col1, col2, col3, col5 FROM tablename

您可以添加到第二项选择:

WHERE col5 IS NOT NULL

如果这是您想要的。

答案 2 :(得分:0)

我会使用cross apply

select v.*
from t cross apply
     (values (id, name, col1, col2, col3, col4),
             (id, name, col1, col2, col3, col5)
     ) v(id, name, col1, col2, col3, col4);

如果您想取消透视并明确排除null值:

select v.*
from t cross apply
     (values (id, name, col1, col2, col3, col4),
             (id, name, col1, col2, col3, col5),
             (id, name, col1, col2, col3, col6)
     ) v(id, name, col1, col2, col3, col4)
where col4 is not null;