如何在下表中获得与每个最小值和最大值对应的行号

时间:2018-06-09 09:34:34

标签: sql postgresql group-by

我有一个表格,其中包含如下所示的架构 enter image description here

对于每个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

非常感谢帮助

3 个答案:

答案 0 :(得分:1)

您可以使用:

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;

答案 1 :(得分:1)

另一种方式:

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

答案 2 :(得分:1)

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;