1

I have a question about union in SQL.

I have this type of table in long-format.

id value key
1 67 users
2 42 users
1 45 politics
2 89 politics

The code should yield something like this (i.e. a table in wide-format):

id users politics
1 67 45
2 42 89

Is this possible to achieve by SQL?

Rick James
  • 135,179
  • 13
  • 127
  • 222
Eugene
  • 31
  • 6

1 Answers1

0

You don't want union. You want to pivot the data. One method uses conditional aggregation:

select id,
       max(case when key = 'users' then value end) as users,
       max(case when key = 'politics' then value end) as politics
from t
group by id;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786