我有一个PostgreSQL表,需要根据不同的列组(每个时间组由不同列的组合)选择第一条记录。
table1 (id1, id2, id3, id4, u1, u2, u3, ...)
我尝试了这段代码,它工作正常。
select
t.*,
row_number() over (partition by id1, id2) as rn1,
row_number() over (partition by id1, id3) as rn2,
row_number() over (partition by id1, id2, id4) as rn3
from table1 t
我只需要每组的第一条记录(rn1 = 1,rn2 = 1,rn3 = 1)。
case when rn1 = 1 and u1 > 0 then 1 else 0 as res1
case when rn2 = 1 and u2 = 1 then 1 else 0 as res2
case when rn3 = 1 and u3 < 0 then 1 else 0 as res3
但是此查询非常慢,需要在不使用任何窗口函数的情况下将其重写。反正有做吗?