我一直在努力,非常感谢您的帮助:
我有两桌车和游乐设施
cars
car_id car_manuf car_model
1 Honda CRV
2 Honda Accord
3 Toyota Corolla
4 Toyota Camry
5 Ford Fusion
rides
ride_id car_id ride_destination
1 3 Boston
2 5 New York
3 5 Washington DC
4 1 California
5 2 Dallas
6 5 Canada
我想按每种汽车类型计算出乘车次数,这些乘车类型将具有car_manuf和car_model的组合,并且应按从最多到最少的乘车次数排序。
输出应为:
CarType-NumberofRides
Honda_CRV-1
Honda_Accord-1
Toyota_Corolla-1
Toyota_Camry-0
Ford_Fusion-3
排序输出与最少的游乐设施
CarType-NumberofRides
Toyota_Camry-0
Honda_Accord-1
Toyota_Corolla-1
Honda_CRV-1
Ford_Fusion-3
mycode:
select
c.car_manuf + '_' + c.car_model AS 'Car Type',
(select count(*) from rides r where r.car_id = c.car_id) AS 'Number of Rides'
from cars c;
我有点卡在这里,不确定如何获得正确的输出。
最佳答案
GROUP BY
发生时必须使用ORDER BY
和COUNT
。我用CONCAT
连接字符串而不是+号。使发生的事情更清晰,并且不会误认为算术运算。
SELECT CONCAT(c.car_manuf, '_', c.car_model) AS CarType, COUNT(r.car_id) AS NumberOfRides
FROM rides r
LEFT JOIN cars c ON (r.car_id = c.car_id)
GROUP BY CarType
ORDER BY NumberOfRides ASC
但是,这省略了0次出现。
如果您还希望看到0,则将表顺序交换为:
SELECT CONCAT(c.car_manuf, '_', c.car_model) AS CarType, COUNT(r.car_id) AS NumberOfRides
FROM cars c
LEFT JOIN rides r ON (r.car_id = c.car_id)
GROUP BY CarType
ORDER BY NumberOfRides ASC
关于mysql - 如何在同一张表中合并两列并计算其唯一出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35513961/