PostgreSQL:获取每个 ID 列的第一个和最后一个插入记录
PostgreSQL : Get first and last inserted record for each ID column
我有以下 table 两列。
Table:
create table tbl1
(
p_id int,
p_price int
);
插入:
INSERT INTO tbl1 values(1,100);
INSERT INTO tbl1 values(1,50);
INSERT INTO tbl1 values(1,20);
INSERT INTO tbl1 values(2,10);
INSERT INTO tbl1 values(2,20);
INSERT INTO tbl1 values(3,22);
INSERT INTO tbl1 values(3,89);
INSERT INTO tbl1 values(3,500);
查询:以下查询为我提供了每行的行号。
SELECT p_id,p_price,row_number() over(partition by p_id order by p_id) rn
from tbl1
我只想获取每个产品 ID (p_id) 的第一个和最后一个插入记录。
预期结果:
p_id p_price
-----------------
1 100
1 20
2 10
2 20
3 22
3 500
您可以使用子查询来做到这一点:
SELECT p_id, p_price, rn from (
SELECT *, last_value(rn) over(partition by p_id) as last from (
SELECT p_id,p_price,row_number() over(partition by p_id order by p_id) rn
FROM tbl1
) s1
) s2 where rn=1 or rn=last;
因此,在内部 select 处,您按分区获取行号,再往上一层,您获取最后的行号(第一个始终为 1)。
然后顶层可以做过滤。
我有以下 table 两列。
Table:
create table tbl1
(
p_id int,
p_price int
);
插入:
INSERT INTO tbl1 values(1,100);
INSERT INTO tbl1 values(1,50);
INSERT INTO tbl1 values(1,20);
INSERT INTO tbl1 values(2,10);
INSERT INTO tbl1 values(2,20);
INSERT INTO tbl1 values(3,22);
INSERT INTO tbl1 values(3,89);
INSERT INTO tbl1 values(3,500);
查询:以下查询为我提供了每行的行号。
SELECT p_id,p_price,row_number() over(partition by p_id order by p_id) rn
from tbl1
我只想获取每个产品 ID (p_id) 的第一个和最后一个插入记录。
预期结果:
p_id p_price
-----------------
1 100
1 20
2 10
2 20
3 22
3 500
您可以使用子查询来做到这一点:
SELECT p_id, p_price, rn from (
SELECT *, last_value(rn) over(partition by p_id) as last from (
SELECT p_id,p_price,row_number() over(partition by p_id order by p_id) rn
FROM tbl1
) s1
) s2 where rn=1 or rn=last;
因此,在内部 select 处,您按分区获取行号,再往上一层,您获取最后的行号(第一个始终为 1)。 然后顶层可以做过滤。