Assuming that ("dateId", "userId")
is unique and new rows always have a bigger (later) dateId
.
After some comments:
What I think you need:
SELECT "dateId", "userId", "Salary"
FROM (
SELECT "dateId", "userId", "Salary"
,(row_number() OVER (PARTITION BY "userId" -- either this
ORDER BY "dateId")) % 2 AS rn
FROM user_table
WHERE "userId" = 789 -- ... or that
) sub
WHERE sub.rn = 1
AND "Salary" > 0;
Notice the PARTITION BY
. This way you skip every second dateId
for each userId
, and additional (later) rows don't change the selection so far.
Also, as long as you are selecting rows for a single userId
(WHERE "userId" = 789
), pull the predicate into the subquery, achieving the same effect (stable selection for a single user). You don't need both.
The WHERE
clause in the subquery only works for a single user, PARTITION BY
works for any number of users in one query.
Is that it? Is it?
They should give me "detective" badge for this.
Seriously.