如何获得每组第二高的值?

Ron*_*ohn 1 postgresql select greatest-n-per-group max postgresql-9.6

从表中获取第二高值已经解决了很多次,但我正在寻找每组中的第二高值。

鉴于此表:

+----+-----+
| A  |  10 |
| A  |  20 |
| A  |  35 |  <-- This record
| A  |  42 |
| B  |  12 |
| B  |  21 |  <-- This record
| B  |  33 |
| C  |  14 |
| C  |  23 |
| C  |  38 |
| C  |  41 |  <-- This record
| C  |  55 |
+----+-----+
Run Code Online (Sandbox Code Playgroud)

我想获得标记的行。
伪代码:

select col_a, penultimate(col_b)
from foo
group by col_a;
Run Code Online (Sandbox Code Playgroud)

小智 6

为此,您可以使用窗口函数。

select col_a, col_b
from (
  select col_a, 
         col_b, 
         dense_rank() over (partition by col_a order by col_b desc) as rnk
  from the_table
) t
where rnk = 2
Run Code Online (Sandbox Code Playgroud)