繁体   English   中英

如何获取下表中每个最小和最大对应的行号

[英]How do I get the row number corresponding to each min and max in the table below

我有一张表,其架构如下所示 在此处输入图片说明

对于每个id,我想要对应于max(h)的n1和对应于min(l)的n2,其中n1和n2是行号

Expected output
id    n1    n2
1      3    10
and similar for each id   

如果最大或最小值重复多次,则仅考虑第一个

select n1, max(h), n2, min(l) from t group by id

它给我一个错误

ERROR:  column "n1" must appear in the GROUP BY clause or be used in an aggregate function

非常感谢帮助

您可以使用:

SELECT t.id,
       MIN(CASE WHEN t.h = sub.h1 THEN n1 END) AS n1,
       MIN(CASE WHEN t.l = sub.l1 THEN n2 END) AS n2
FROM tab_name t
JOIN (SELECT id, MAX(h) AS h1, MIN(l) AS l1
      FROM tab_name
      GROUP BY id) sub
  ON t.id = sub.id
 AND (t.h = sub.h1 OR t.l = sub.l1)
GROUP BY t.id;

其他方式:

SELECT id, 
       min(h) as min_h,
       max(h) as max_h,
       max( case when low_rn = 1 then n1 end) as n1_for_min,
       min( case when high_rn = 1 then n1 end) as n1_for_max
FROM (
  SELECT *,
        row_number() over (partition by id order by h) as low_rn,
        row_number() over (partition by id order by h desc) as high_rn
  FROM mytable
) x 
WHERE 1 IN (low_rn, high_rn)
GROUP BY id

演示: https : //dbfiddle.uk/?rdbms=postgres_10&fiddle=35fcb41891a8a446bcb55f0a6fd0a774

Postgres具有非常方便的first_value()函数,该函数可以执行您想要的操作。 几乎。 唯一的不便是它是窗口函数,而不是分析函数。 可以使用select distinct来解决:

select distinct id,
       first_value(n1) over (partition by id order by h desc) as n1_at_max_h,
       first_value(n2) over (partition by id order by l desc) as n2_at_max_l
from t;

这可能是解决此问题的最简单方法。

如果您喜欢聚合,则可以使用:

select id,
       ( array_agg(n1 order by h desc) )[1] as n1_at_max_h,
       ( array_agg(n2 order by l desc) )[1] as n2_at_max_l
from t
group by id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM