2012-03-13 61 views
5

列我有产生以下结果一个简单的查询:移调MySQL查询行到

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

我想行转置成列。

我知道mysql没有pivot函数,所以需要union但不是100%肯定。

在此先感谢您的帮助。

+1

可能重复[如何透视一个MySQL实体 - 属性值模式](http://stackoverflow.com/questions/649802/how-to-pivot-a-mysql-entity-attribute-value-schema) – 2012-03-13 14:08:13

+1

通过这个[http://stackoverflow.com/questions/1851781/transpose-a-row-into-columns-with-mysql-without-using-unions]可能会帮助你。 – Java 2012-03-13 14:23:57

回答

7

你可以用这样的交叉做到这一点 -

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。

+1

@RyanSmith(note),这个答案应该为你做,但是,如果你跨年活动,你可能需要考虑增加YEAR作为一个额外的组。你不会希望将虚假数字推到一年。 – DRapp 2012-03-13 15:17:28

+1

@DRapp感谢您的注意。我将修改我的查询以包含年份。 – nnichols 2012-03-13 15:27:13

+0

非常感谢,百分百工作。 – Smudger 2012-03-13 17:55:17