postgresql利用開窗函數取附近行的數據、階段累加、添加序號

建表並插入數據

  • 建表語句
create table test1
(
    id          bigserial not null
        constraint test1_pk
            primary key,
    create_time timestamp default now()
);
  • 插入隨機時間
insert into test1(create_time)
values (timestamp '2019-01-01' + random() * (timestamp '2019-01-01' - timestamp '2019-12-31')),
       (timestamp '2019-01-01' + random() * (timestamp '2019-01-01' - timestamp '2019-12-31')),
       (timestamp '2019-01-01' + random() * (timestamp '2019-01-01' - timestamp '2019-12-31')),
       (timestamp '2019-01-01' + random() * (timestamp '2019-01-01' - timestamp '2019-12-31')),
       (timestamp '2019-01-01' + random() * (timestamp '2019-01-01' - timestamp '2019-12-31'))

獲取下一行時間

select *,
       lead(create_time, 1) over (order by create_time) next_time,
       lead(id, 1) over (order by create_time)          next_id
from test1		
  • lead是把下一行的拉上來,lag是把上一行的拉下來
  • 第二個參數是位移參數,lead(id,2)就是把向下第二行的拉上來

結果

id create_time next_time next_id
3 2018-01-19 07:46:52.866604 2018-02-14 04:53:51.180972 1
1 2018-02-14 04:53:51.180972 2018-06-27 02:28:08.436520 4
4 2018-06-27 02:28:08.436520 2018-11-17 12:49:05.837975 5
5 2018-11-17 12:49:05.837975 2018-12-31 02:00:36.177528 2
2 2018-12-31 02:00:36.177528 null null

階段累加

select id,
       sum(id) over (order by create_time) sum_id,
       create_time
from test1

結果

id sum_id create_time
3 3 2018-01-19 07:46:52.866604
1 4 2018-02-14 04:53:51.180972
4 8 2018-06-27 02:28:08.436520
5 13 2018-11-17 12:49:05.837975
2 15 2018-12-31 02:00:36.177528
  • 同理可以用在如avg,max,min之類的聚合函數

添加序號

select id,
       row_number() over (order by create_time) number,
       create_time
from test1

結果

id number create_time
3 1 2018-01-19 07:46:52.866604
1 2 2018-02-14 04:53:51.180972
4 3 2018-06-27 02:28:08.436520
5 4 2018-11-17 12:49:05.837975
2 5 2018-12-31 02:00:36.177528
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章