I'm trying to select a value from a table like the following example:
user id
----------
a 1
b 1
c 3
d 2
a 3
and the result will be like the following:
user id_1 id_2 id_3
-----------------------
a 1 NULL 3
b 1 NULL NULL
c NULL NULL 3
d NULL 2 NULL
so basically what I'm trying to accomplish is to get all the users with id's ==1
to a column and the users with id ==2
to another column and users with id ==3
to a third column and the users are duplicated like the case for user 'a'
when it showed once with id=1
and id=3
and I want to capture this duplication in the resulting table.
Any idea would be appreciated. Thanks in advance!
This is called a pivot. You can do this with conditional aggregation:
select user,
max(case when id = 1 then id end) as id_1,
max(case when id = 2 then id end) as id_2,
max(case when id = 3 then id end) as id_3
from table t
group by user
order by user;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.