如果我有这张桌子:
+----+--------+--------+--------+--------+
| ID | Field1 | Field2 | Field3 | Field4 |
+----+--------+--------+--------+--------+
| 1 | Foo | | Bar | Baz |
| 2 | | Baz | | |
| 3 | | Dolor | Bob | |
| 4 | Lorem | | | Test |
| 5 | | Ipsum | | |
| 6 | Foo | Bar | Baz | Test |
+----+--------+--------+--------+--------+
如何选择单行,并将非空列作为列表返回?
例如,如果我有这个(不完整的)陈述:SELECT [...] AS Columns FROM [MyTable] WHERE ID = 1
,我希望看到这个结果:
+---------+
| Columns |
+---------+
| Foo |
| Bar |
| Baz |
+---------+
这个select语句看起来怎么样?
答案 0 :(得分:4)
试试这个:
SELECT x.Field
FROM YourTable t
CROSS APPLY
(
VALUES
(t.Field1),
(t.Field2),
(t.Field3),
(t.Field4)
) x (Field);
WHERE t.ID = 1 AND field IS NOT NULL
答案 1 :(得分:0)
试试这个,
select feild from
(select * from @t where id=1)t4
unpivot(orders for feild in(Field1,Field2,Field3,Field4))pvt