sql - 在Postgres中,如何获得具有最大值的子分组?

标签 sql postgresql aggregate-functions

在 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/

相关文章:

mysql - 按非数据库字段分组

c# - 在 EF Core 中执行两个相关操作

sql - 将列中的数组与另一个查询的计数结果相乘

ruby-on-rails-3 - OSX Mavericks 后 Postgres 配置搞砸了

sql - 如何对位列使用 SUM?

sql - 合并多个表中的最新条目

c# - 如何删除 datagridview 中的行并同时更新 Access 中的数据库

mysql - 如何按 ID 序列使用 where 子句

sql - 如何在 Sqlite 中设置表来进行递归查询?

ruby-on-rails - 具有连接和顺序的不同记录