将简单的单列3行结果转换为单行,3列结果?

时间:2014-08-16 23:01:00

标签: mysql sql

我有一个统计查询,它将返回三行(因为我有3种类型,我按其分组),我也知道行的顺序,因为我明确ORDER BY FIELD

SELECT COUNT(id) AS c FROM Vehicles GROUP BY VehicleTypeID ORDER BY FIELD(VehicleTypeID, 1,2,3)

有没有一种简单的方法将行转换为列?类似(PSEUDO SQL)

SELECT c[0] AS CarsCount, c[1] AS MotorcyclesCount, c[2] AS TrucksCount FROM (
     SELECT COUNT(id) AS c 
     FROM Vehicles 
     GROUP BY VehicleTypeID 
     ORDER BY FIELD(VehicleTypeID, 1,2,3)
)

1 个答案:

答案 0 :(得分:1)

是的,它是带有聚合的case语句:

SELECT max(case when fieldnum = 1 then c end) AS CarsCount, 
       max(case when fieldnum = 2 then c end) AS MotorcyclesCount, 
       max(case when fieldnum = 3 then c end) AS TrucksCount
FROM (SELECT COUNT(id) AS c , FIELD(VehicleTypeID, 1,2,3) as fieldnum
      FROM Vehicles 
      GROUP BY VehicleTypeID 
     ) t;