I have a PostgreSQL table and need to select the first record based on different groups of columns (each time group by a combination of different columns).
table1 (id1, id2, id3, id4, u1, u2, u3, ...)
I tried this code and it works fine.
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
and I need only the first records from each group (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
But this query is very slow and need to rewrite it without using any window function. Is there anyway to do it?
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
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