MySQL-如何从一列中查询具有不同值的不同列

时间:2018-07-08 15:49:44

标签: mysql sql

我试图用一列创建具有不同值的不同列...我仍然不知道如何处理此请求。我有这样的表

No  Description   Delivery  unit
1   Shipment to A   Car     2
2   Shipment to B   plane   4
3   Shipment to C   Ship    3
4   Shipment to A   Car     1
5   Shipment to C   Ship    2

我想创建类似这样的东西

no  description        Car   Plane  Ship
1   shipment to all     3      4     5

如何实现这一目标...

提前谢谢。

1 个答案:

答案 0 :(得分:4)

您可以使用条件聚合:

select 1 as no, 'Shipment to all' as description,
       sum(case when delivery = 'Car' then unit else 0 end) as car,
       sum(case when delivery = 'plane' then unit else 0 end) as plane,
       sum(case when delivery = 'ship' then unit else 0 end) as ship
from t;

目前尚不清楚前两列的计算方式,因此我只包含了常量。