0

If I have this table:

+----+--------+--------+--------+--------+
| ID | Field1 | Field2 | Field3 | Field4 |
+----+--------+--------+--------+--------+
| 1  | Foo    |        | Bar    | Baz    |
| 2  |        | Baz    |        |        |
| 3  |        | Dolor  | Bob    |        |
| 4  | Lorem  |        |        | Test   |
| 5  |        | Ipsum  |        |        |
| 6  | Foo    | Bar    | Baz    | Test   |
+----+--------+--------+--------+--------+

How can I select a single row, and have the non-null columns returned as a list?

For example, if I have this (incomplete) statement: SELECT [...] AS Columns FROM [MyTable] WHERE ID = 1, I would like to see this as the result:

+---------+
| Columns |
+---------+
| Foo     |
| Bar     |
| Baz     |
+---------+

How would this select statement look?

qJake
  • 16,821
  • 17
  • 83
  • 135
  • seems to be kind of similar to http://stackoverflow.com/questions/5031204/does-t-sql-have-an-aggregate-function-to-concatenate-strings – slartidan Mar 05 '14 at 15:50
  • 1
    @slartidan No, that's string concatenation, I'm talking about selecting arbitrary columns from a single row, as one column with a bunch of rows (essentially a list). – qJake Mar 05 '14 at 15:52

2 Answers2

4

Try this:

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
Lamak
  • 69,480
  • 12
  • 108
  • 116
  • This works, but includes null fields. In your example, "Field2" is null and should not be included. How can I filter out null values? – qJake Mar 05 '14 at 16:13
  • @SpikeX Sorry, I forgot about that requirement. Updated my answer now – Lamak Mar 05 '14 at 16:14
  • Oops, my fields were actually `''`, not `NULL`, but that was easy to change. Thanks! – qJake Mar 05 '14 at 16:19
0

try this,

select feild from 
(select * from @t where id=1)t4
unpivot(orders for feild in(Field1,Field2,Field3,Field4))pvt
KumarHarsh
  • 5,046
  • 1
  • 18
  • 22