我正在尝试建立一个系统,找到一个行程最多的停靠点列表(stop_code)。
像:
SELECT count(`trip_id`) as `count` FROM `stop_times`
WHERE `time` BETWEEN '13:00:00' AND '13:05:00'
GROUP BY `stop_code`
ORDER BY `count` DESC
但是,因为,我正在拉结果
stop code: 3000 count: 9
stop code: 3011 count: 7
stop code: 3030 count: 3
在这些计数中,我们可以说,它包括:
stop code: 3000 list: trip1,trip2,trip3,trip4,trip5,trip6,trip7,trip8,trip9
stop code: 3011 list: trip3,trip4,trip5,trip6,trip7,trip10,trip11
stop code: 3030 list: trip2,trip3,trip4,trip12
如何调整该查询,让它说:
stop code: 3000 list: trip1,trip2,trip3,trip4,trip5,trip6,trip7,trip8,trip9
stop code: 3011 list: trip10,trip11
stop code: 3030 list: trip12
在一组独特的trip_id
。
由于
答案 0 :(得分:1)
在进行计数之前,使用每个stop_code
获得最低trip_id
的子查询。
SELECT stop_code, COUNT(*) AS count
FROM (SELECT trip_id, MIN(stop_code) AS stop_code
FROM stop_times
WHERE `time` BETWEEN '13:00:00' AND '13:05:00'
GROUP BY trip_id) AS x
GROUP BY stop_code
ORDER BY count DESC