我一直在努力,非常感谢一些帮助:
我有两张桌子车和游乐设施
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;
我有点卡在这里,不知道在获得正确的输出方面我应该走哪个方向。
答案 0 :(得分:0)
当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