【问题标题】:Highest per each group每组最高
【发布时间】:2015-03-23 09:35:00
【问题描述】:

这里很难显示我的实际表和数据,所以我将用一个示例表和数据来描述我的问题:

create table foo(id int,x_part int,y_part int,out_id int,out_idx text);

insert into foo values (1,2,3,55,'BAK'),(2,3,4,77,'ZAK'),(3,4,8,55,'RGT'),(9,10,15,77,'UIT'),
                       (3,4,8,11,'UTL'),(3,4,8,65,'MAQ'),(3,4,8,77,'YTU');

以下是表格foo

id x_part y_part out_id out_idx 
-- ------ ------ ------ ------- 
3  4      8      11     UTL     
3  4      8      55     RGT     
1  2      3      55     BAK     
3  4      8      65     MAQ     
9  10     15     77     UIT     
2  3      4      77     ZAK     
3  4      8      77     YTU     

我需要通过对每个out_id最高 id 进行排序来选择所有字段。
预期输出:

id x_part y_part out_id out_idx 
-- ------ ------ ------ ------- 
3  4      8      11     UTL     
3  4      8      55     RGT     
3  4      8      65     MAQ     
9  10     15     77     UIT     

使用 PostgreSQL。

【问题讨论】:

标签: sql postgresql greatest-n-per-group


【解决方案1】:

Postgres 特定(和最快)的解决方案:

select distinct on (out_id) *
from foo
order by out_id, id desc;

使用window function(第二快)的标准 SQL 解决方案

select id, x_part, y_part, out_id, out_idx
from (
  select id, x_part, y_part, out_id, out_idx, 
         row_number() over (partition by out_id order by id desc) as rn
  from foo
) t
where rn = 1
order by id;

请注意,即使有多个相同的 out_id 值,两种解决方案都只会返回每个 id 一次。如果您希望它们全部返回,请使用 dense_rank() 而不是 row_number()

【讨论】:

    【解决方案2】:
    select * 
    from foo 
    where (id,out_id) in (
    select max(id),out_id from foo group by out_id
    ) order by out_id
    

    【讨论】:

      【解决方案3】:

      查找max(val) := 查找不存在更大val 的记录:

      SELECT * 
      FROM foo f
      WHERE NOT EXISTS (
         SELECT 317
         FROM foo nx
         WHERE nx.out_id = f.out_id
         AND nx.id > f.id
         );
      

      【讨论】:

      • 不错的一个。 where out_id > all (select .. ) 是它的另一种变体。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多