ralexa11
ralexa11

Reputation: 1

SQL how to collapse multiple columns into two columns, one for column heading and the second for column value

If the input data looks like this:

Key Col1 Col2 Col3 Col4
keyA val1 val2 val3 val4
keyB val1 val2 val3 val4

How can I convert it to look like this?

Key ColTitle ColVal
keyA Col1 val1
keyA Col2 val2
keyA Col3 val3
keyA Col4 val4
keyB Col1 val1
keyB Col2 val2
keyB Col3 val3
keyB Col4 val4

Upvotes: 0

Views: 476

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270663

One method is union all:

select key, 'Col1' as coltitle, col1 as colval
from t
union all
select key, 'Col2' as coltitle, col2 as colval
from t
union all
select key, 'Col3' as coltitle, col3 as colval
from t
union all
select key, 'Col4' as coltitle, col4 as colval
from t

Upvotes: 0

Related Questions