表中資料如下, table, lane, pos,三串列示位置,取出所有位置( table, lane, pos相同)按時間最近的兩條資料。
表的資料大概幾十萬行
id table lane pos wu nan create_time
1 2 1 1 aaa bbbbb 2020-6-25 01:03:01.456
2 1 2 1 cccc dddd 2020-6-25 02:00:01.456
3 1 2 1 aaa bbb 2020-6-25 03:00:01.456
4 2 1 1 ffff 333 2020-6-25 04:06:01.456
5 2 1 1 aaa bbb 2020-6-25 05:00:01.456
6 1 2 1 ffff 333 2020-6-25 06:00:01.456
7 2 1 1 aaa bbb 2020-6-25 07:00:01.456
8 2 1 1 ffff 333 2 020-6-25 08:08:01.456
9 1 1 3 ffff 333 2020-6-25 09:00:01.456
10 1 1 3 ffff 333 2020-6-25 10:00:01.456
11 1 1 3 aaa bbb 2020-6-25 11:09:01.456
12 3 2 1 ffff 333 2020-6-25 12:00:01.456
13 3 2 1 aaa bbb 2020-6-25 13:00:01.456
14 3 2 1 ffff 333 2020-6-25 14:09:01.456
15 3 2 1 ffff 333 2020-6-25 15:00:01.456
uj5u.com熱心網友回復:
直接用分組函式就可以實作啦;按照那三列分組,組內按照時間倒序
select table,lane ,pos from (
select table,lane ,pos,
ROW_NUMBER() over(partition by table,lane,pos order by create_time desc ) from test) as a
where n<3
uj5u.com熱心網友回復:
用分組函式,按照table, lane, pos分組,組內按照時間排序,用Lag函式來計算相鄰行的時間差即可。uj5u.com熱心網友回復:
沒看懂哈,把sql執行報錯。n 是什么?
uj5u.com熱心網友回復:
嗯,忘了賦別名了;你可以補充一下Row_number函式的知識
select table,lane ,pos from (
select table,lane ,pos,
ROW_NUMBER() over(partition by table,lane,pos order by create_time desc ) as n from test) as a
where n<3
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/11799.html
標籤:PostgreSQL
上一篇:vfp排課
下一篇:自考資料庫
