提取每个窗口的最小值

提取每个窗口的最小值

我的数据如下:

 IP        username   time1
-----      ------      -----
1.2.3.4      abc      01:00
1.2.3.4      abc      02:00
1.2.3.4      abc      03:00
1.2.3.4      pqr      04:00
1.2.3.4      pqr      05:00
1.2.3.4      pqr      06:00
1.2.3.4      pqr      07:00
1.2.3.4      abc      08:00
1.2.3.4      abc      09:00
1.2.3.5      abc      10:00
1.2.3.5      abc      11:00

我想提取每个窗口的最小值。也就是说,我希望我的输出
IP        username   time1
-----      ------      -----
1.2.3.4      abc      01:00
1.2.3.4      pqr      04:00
1.2.3.4      abc      08:00
1.2.3.5      abc      10:00

我想做这样的事:
select ip, usrnm, time1
from (select ROW_NUMBER() over(partition by ip, usrnm order by time1)as
rownum,ip, usrnm, time1 from table1)t2
where t2.rownum = 1

但我无法捕捉
1.2.3.4 abc 08:00

有线索吗?

最佳答案

使用lag()检查记录是否是“组”中的第一个。

SELECT ip,
       username,
       time1
       FROM (SELECT ip,
                    username,
                    time1,
                    coalesce(lag(ip) OVER (ORDER BY time1) <> ip
                              OR lag(username) OVER (ORDER BY time1) <> username,
                             true) x
                    FROM elbat) x
       WHERE x;

db<>fiddle

关于sql - POSTGRESQL:提取每个窗口的最小值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53825009/

10-12 19:19