I have a table like below:
Table A
----------
ID Field1 Field2 Field3
1 A NULL B
2 B NULL NULL
3 C A NULL
4 A D NULL
The requirement is to combine all the Fields (except ID) into one, so that Table will look like as below:
Table A
-------
ID Field
1 A
2 B
3 C
4 D
Any order will be okay though the values have to be distinct. This means that Field1 to Field3 needs to be one column (in any temp table) and have distinct values. I used ID columns just to clarify the result however ID is not required. Currently I’m using union for the desired output
e.g.
select distinct Field
from
(Select Field1 as Field from TableA
where Field1 is not null
union
Select Field2 from TableA
where Field2 is not null
union
Select Field3 from TableA
where Field3 is not null
)
I’m sure that there is better way of achieving the same output with less line of codes.
I think your
UNIONsolution is about as close as you can get to what you want. I would clean it up a little though, like this:I tightened up the sub query by moving the
WHEREclause to the outside. Also, you don’t needDISTINCTon the outside, sinceUNIONalready provides a distinct result.