合并具有相同ID的行

时间:2018-09-13 13:17:59

标签: sql merge rows

我有下表:

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

如何查询以获得该结果:

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         |                |                |

每个ID的最大变体数量为2。

谢谢!

3 个答案:

答案 0 :(得分:0)

它将在sql server / posgresql / oracle中工作-使用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

答案 1 :(得分:0)

您可以使用row_number()进行条件聚合:

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;

答案 2 :(得分:0)

尝试左加入自己的行:

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