Skip to content
Advertisement

SQL query for key and value

I need to write a query that does the following. After searching various forums I see “PIVOT” is one of the ways to implement this. I am still trying to write an query using PIVOT but in the meantime can anyone suggest if there is any other alternate way to do the same?

TABLE T1

s_ID | a_ID
------------
 1   |  a1
------------
 2   |  a2
------------

 TABLE T2
a_ID | Key | Value
a1   | k1  | v1
a1   | k2  | v2
a1   | k3  | v3
a2   | k1  | v1
a2   | k2  | v2
a2   | k4  | v4

OUTPUT from query expected:

s_ID | a_ID | k1 | k2 | k3 | k4
---------------------------------
 1   | a1   | v1 | v2 | v3 |
---------------------------------
 2   | a2   | v1 | v2 |    | v4 

Advertisement

Answer

use conditional aggregation

select s_id,t1.a_id, max(case when key='k1' then value end),
max(case when key='k1' then value end),
max(case when key='k2' then value end),
max(case when key='k3' then value end) from table1 t1 join table2 t2 on t1.a_ID=t2.a_ID
 group by s_id,t1.a_id
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement