如何在Postgresql的一行中获取第一个和最后一个值[关闭]
Posted
技术标签:
【中文标题】如何在Postgresql的一行中获取第一个和最后一个值[关闭]【英文标题】:How to get first and last value on one row in Postgresql [closed] 【发布时间】:2020-09-24 23:58:46 【问题描述】:输入:
postgres=> select player_1, row_number() over (order by id) as r1, row_number() over (order by id desc) as r2 from (select id, player_1 from matches order by id limit 5) as foo;
player_1 | r1 | r2
--------------------+----+----
Kafelnikov Yevgeny | 1 | 5
Dreekmann Hendrik | 2 | 4
Courier Jim | 3 | 3
Krajicek Richard | 4 | 2
Rafter Patrick | 5 | 1
(5 rows)
预期:
first | last
--------------------+----+----
Kafelnikov Yevgeny | Rafter Patrick
我尝试了以下方法,但它有 5 行,我需要它们都放在一行上,就像上面一样。
postgres=> select case when r1 = 1 then player_1 end, case when r2 = 1 then player_1 end from (select player_1, row_number() over (order by id) as r1, row_number() over (order by id desc) as r2 from (select id, player_1 from matches order by id limit 5) as foo) as too;
case | case
--------------------+----------------
Kafelnikov Yevgeny |
|
|
|
| Rafter Patrick
(5 rows)
【问题讨论】:
【参考方案1】:你在正确的轨道上。您可以使用这些行号进行条件聚合:
select
max(player_1) filter(where r1 = 1) first_player,
max(player_1) filter(where r2 = 1) last_player
from (
select player_1,
row_number() over (order by id) as r1,
row_number() over (order by id desc) as r2
from (select * from matches order by id limit 5) t
order by id limit 5
) t;
请注意,您也可以使用 first_value()
和 distinct
执行此操作:
select distinct
first_value(player_1) over(order by id) first_player,
first_value(player_1) over(order by id desc) last_player
from (select * from matches order by id limit 5) t
Demo on DB Fiddle
【讨论】:
【参考方案2】:另一种方法如下 -
select
max(case when r1 = 1 then player_1 end) as first_player,
max(case when r2 = 1 then player_1 end) as last_player
from (
select player_1,
row_number() over (order by id) as r1,
row_number() over (order by id desc) as r2
from (select * from mytable order by id limit 3) t
order by id limit 5
) t;
【讨论】:
以上是关于如何在Postgresql的一行中获取第一个和最后一个值[关闭]的主要内容,如果未能解决你的问题,请参考以下文章