在 Postgres 中,我有一个具有以下结构的地铁系统的历史表:
CREATE TABLE stop_history
(
stop_id character varying,
route_id character varying,
next_stop_id character varying
);
我正在尝试弄清楚: 对于站点和路线,最常见的下一站是什么?
我需要做的是: 按站点、路线和下一站进行分组,并获取这些组的计数。 对于每个组,获取每个 stop_id 和 Route_id 组合计数最高的组。
我将如何编写这样的 postgres 查询,以及我应该在此表上放置哪些索引以最大限度地提高性能?
我遇到的挑战之一是无法在 where 子句中使用 count(*)
或 max(count(*))
。
样本数据:
INSERT INTO stop_history VALUES ('101N', '1', NULL);
INSERT INTO stop_history VALUES ('102N', '1', '101N');
INSERT INTO stop_history VALUES ('103N', '1', '102N');
INSERT INTO stop_history VALUES ('104N', '1', '103N');
INSERT INTO stop_history VALUES ('104N', '1', '103N');
INSERT INTO stop_history VALUES ('104N', '1', '102N');
INSERT INTO stop_history VALUES ('104N', '1', '103N');
INSERT INTO stop_history VALUES ('104N', '1', '102N');
INSERT INTO stop_history VALUES ('101N', 'D', NULL);
INSERT INTO stop_history VALUES ('102N', 'D', '101N');
INSERT INTO stop_history VALUES ('102N', 'D', '101N');
INSERT INTO stop_history VALUES ('102N', 'D', NULL);
预期输出是:
Stop | Route | Most common Next Stop | Frequency
101N 1 NULL 1
102N 1 101N 1
103N 1 102N 1
104N 1 103N 3
101N D NULL 1
102N D 101N 2
最佳答案
类似这样的事情:
select distinct on (stop_id, route_id) stop_id,
route_id,
coalesce(next_stop_id, 'NULL'),
count(*) over (partition by route_id, stop_id, coalesce(next_stop_id, 'NULL')) as frequency
from stop_history
order by route_id, stop_id, frequency desc
窗口函数 ( count(*) over (...)
) 计算 next_stop_id
的频率柱子。
(Postgres) 特定 distinct on()
然后用于将结果减少到仅具有最高频率的结果(这是通过最终的 order by ... frequence DESC
实现的)
SQLFiddle:http://sqlfiddle.com/#!15/66ff6/1
关于sql - 在Postgres中,如何获得具有最大值的子分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27986437/