Transform mysql query rows into columns

I have a simple query that gives the following results:

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

I would like to wrap rows in columns.

I understand that mysql does not have support functions, so merging is required, but not 100%.

Thanks in advance for your help.

+5
source share
1 answer

You can do this with a crosstab like this -

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`

In another note, you must transfer the transporttype values ​​to the lookup table and there is transporttype_id in this table.

+7
source

All Articles