如何在单行上显示多行

时间:2018-11-14 11:22:27

标签: sql sql-server grouping

我正在研究一个查询,该查询每个特定的ID包含多行,我希望将它们全部显示在一行上。

我当前拥有的查询是:

SELECT 

person_id,
car_name,
car_year, 
car_value,
car_mileage

FROM tbl_motor_vehicles

这将返回以下内容:

person_id     car_name     car_year      car_value       car_mileage
---------------------------------------------------------------------
1       TOYOTA YARIS      2017          5000            10000
1       Nissan Micra      2001          1000            15000
2       Golf                            15000           700000
2       Fiat Punto        2002          2500            60000

我需要将其显示在每个ID一行上,并且每辆车都有自己的列,如下所示:

Person ID    Car_1_NAME    Car_1_year       car1_value     car1_mileage     Car_2_NAME    Car_2_year       car2_value    car2_mileage
--------------------------------------------------------------------------------------------------------------------------------------
1        TOYOTA YARIS     2017              5000         10000        Nissan Micra       2001             1000          15000
2           Golf          2007              15000       700000        Fiat Punto         2002             2500          60000

谁能建议我该怎么做?

1 个答案:

答案 0 :(得分:0)

SQL查询具有固定数量的列。因此,您只能为每个人显示一组固定的汽车。需要注意的是,您可以使用条件聚合:

SELECT person_id,
       MAX(CASE WHEN seqnum = 1 THEN car_name END) as car_name_1,
       MAX(CASE WHEN seqnum = 1 THEN car_year END) as car_year_1,
       MAX(CASE WHEN seqnum = 1 THEN car_value END) as car_value_1,
       MAX(CASE WHEN seqnum = 1 THEN car_mileage END) as car_mileage_1,
       MAX(CASE WHEN seqnum = 2 THEN car_name END) as car_name_2,
       MAX(CASE WHEN seqnum = 2 THEN car_year END) as car_year_2, 
       MAX(CASE WHEN seqnum = 2 THEN car_value END) as car_value_2,
       MAX(CASE WHEN seqnum = 2 THEN car_mileage END) as car_mileage_2
FROM (SELECT mv.*, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY (SELECT NULL)) as seqnum
      FROM tbl_motor_vehicles mv
     ) mv
GROUP BY person_id;