将mysql查询行转换为列

时间:2012-03-13 14:05:29

标签: mysql rows transpose

我有一个简单的查询,产生以下结果:

SELECT month,transporttype,count(transporttype) as loads 
from deliveries 
group by month,transporttype

我想将行转置为列。

据我所知,mysql没有透视功能所以需要联合但不是100%确定。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:8)

你可以使用这样的交叉表来实现 -

SELECT
    `year`,
    `month`,
    SUM(IF(`transporttype` = 'inbound',                 1, 0)) AS `inbound`,
    SUM(IF(`transporttype` = 'LocalPMB',                1, 0)) AS `LocalPMB`,
    SUM(IF(`transporttype` = 'Long Distance',           1, 0)) AS `Long Distance`,
    SUM(IF(`transporttype` = 'shuttle',                 1, 0)) AS `shuttle`,
    SUM(IF(`transporttype` = 'export',                  1, 0)) AS `export`,
    SUM(IF(`transporttype` = 'Extrusions-LongDistance', 1, 0)) AS `Extrusions-LongDistance`,
    SUM(IF(`transporttype` = 'Extrusions-Shuttle',      1, 0)) AS `Extrusions-Shuttle`
FROM `deliveries`
GROUP BY `year`, `month`

另外,您应该将transporttype值移动到查找表,并在此表中包含transporttype_id。