我有以下表格结构:
cars
- id
- brand
- location
car_services
:
- id
- car_id
- service_id
services
- id
- service_name
我要做的是获取一个service_name
的列表,其中包含某个位置的发生汽车数量(按事件排序)。
例如 - 我想知道德克萨斯州汽车的顶级服务是什么。
我很抱歉,如果我解释我想要复杂的方式 - 如果是这样,我会尝试更好地解释它。
提前谢谢你。
答案 0 :(得分:1)
试试这个......
SELECT service_names
, c.location
, COUNT(c.id) car_occ
FROM services s
INNER JOIN car_services cs
on s.id=cs.service_id
inner join cars c
on s.id=c.id
group by service_names, c.location
答案 1 :(得分:1)
据我所知你想要一个像这样的结果:
service_name | location | count
-------------+------------+------
service 1 | location 1 | 5
service 2 | location 1 | 4
service 1 | location 2 | 2
使用如下查询可以实现:
SELECT services.service_name, cars.location, count(*) as count
FROM services
JOIN car_services on services.id = car_services.service_id
JOIN cars on cars.id = car_services.car_id
GROUP BY services.service_name, cars.location
ORDER BY count DESC