mysql转置_将mysql查询行转置为列

bd96500e110b49cbb3cd949968f18be7.png

I have a simple query that produces the below results:

SELECT month,transporttype,count(transporttype) as loads

from deliveries

group by month,transporttype

I would like to transpose the rows into columns.

I understand mysql does not have pivot functions so a union is required but not 100% sure.

Thanks in advance for the help.

解决方案

You can do it 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`

On a different note, you should move transporttype values to a lookup table and have transporttype_id in this table.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值