I have the following table:
ID | variant_name | variant_color
1 | BMW 7-series | Black
2 | Volvo C60 | Gray
1 | BMW 3-series | White
3 | Subaru Forester| Orange
2 | Volvo XC90 | Green
How can I query to gain this result:
ID | variant_name_1 | variant_color_1| variant_name_2 | variant_color_2|
1 | BMW 7-series | Black | BMW 3-series | White |
2 | Volvo C60 | Gray | Volvo XC90 | Green |
3 | Subaru Forester| Orange | | |
Each ID has a maximum number of variants of 2.
Thanks!
It'll work in sql server/posgresql/oracle - use row_number()
http://sqlfiddle.com/#!18/a7540/10424
select id, max(case when rn=1 then variant_name end) as variant_name1,max(case when rn=1 then variant_color end) as variant_color1,
max(case when rn=2 then variant_name end) as variant_name2,max(case when rn=2 then variant_color end) as variant_color2
from
(
select id, variant_name, variant_color, row_number() over(partition by id order by id) as rn
from tablename)a
group by id
You can use row_number()
to do conditional aggregation :
select id, max(case when seq = 1 then variant_name end) as variant_name_1,
max(case when seq = 1 then variant_color end) as variant_color_1,
max(case when seq = 2 then variant_name end) as variant_name_2,
max(case when seq = 2 then variant_color end) as variant_color_2
from (select t.*, row_number() over (partition by id order by variant_color) as seq
from table t
) t
group by id;
Try left joining with itself:
select c1.id,
c1.variant_name as variant_name_1,
c1.variant_color as variant_color_1,
c2.variant_name as variant_name_2,
c2.variant_color as variant_color_2
from cars c1
left join cars c2
on c1.id = c2.id
and c1.seq <> c2.seq
group by c1.id
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.