雅典娜每组前1名

问题描述 投票:0回答:2

有什么方法可以在不使用 ROW_NUMBER 的情况下实现每个组的前 1 个结果? 下面的table_a已经有10亿行了,所以我想用最高效的方式

下面的查询是我正在使用的。

SELECT *
FROM   (
        SELECT ROW_NUMBER() OVER (PARTITION BY column_a, column_b, column_c ORDER BY column_d) AS row_num,
               *
        FROM   table_a
        )
WHERE  row_num = 1
sql postgresql group-by amazon-athena row-number
2个回答
0
投票

这可以使用

group by
和聚合函数
min()
来完成:

SELECT column_a, column_b, column_c, min(column_d) as top1
FROM table_a
group by column_a, column_b, column_c

0
投票

另一种选择是

distinct on
。然而
distinct on
是 Postgres 扩展而不是 SQL 标准。

select distinct on (column_a, column_b, column_c) 
       column_a, column_b, column_c, column_d as top1
  from table_a
 order by column_a, column_b, column_c, column_d;
© www.soinside.com 2019 - 2024. All rights reserved.