I have a table similar to the following:
id key str_val date_val num_val
1 A a
1 B b
1 C 2012-01-01
1 D 1
2 A c
2 E d
2 C 2012-01-02
2 D 2
I need it to look like:
id A B C D E
1 a b 2012-01-01 1
2 c 2012-01-02 2 d
Basically, each key needs to become it's own column
I tried and failed to use the PIVOT command usefully, and I'm currently trying to accomplish this with a case statement. i.e.
select
id,
case key
when 'A'
then str_val
end as A,
case key
when 'C'
then date_val
end as C
--etc.
from test_table
However I can't figure out how to combine the table rows after this runs. I'm stuck with:
id A B C D E
1 a
1 b
1 2012-01-01
1 1
Any thoughts or input that could help me out? Thanks in advance.
You are 90% of the way there:
As long as id and key are a unique combination per table then you could write your query like:
In this query you get all the IDs (if you can reply on column 'A' always being there you can start with that instead). Then you have to join on each key for the given id.
If you cannot rely on the data type of the key, i.e. A may be String or Date, then you have to use the following for each select: