I was using this SQL statement:
SELECT "dateId", "userId", "Salary"
FROM (
SELECT *,
(row_number() OVER (ORDER BY "userId", "dateId"))%2 AS rn
FROM user_table
) sa
WHERE sa.rn=1
AND "userId" = 789
AND "Salary" > 0;
But every time the table gets new rows the result of the query is different.
Am I missing something?
Assuming that
("dateId", "userId")is unique and new rows always have a bigger (later)dateId.After some comments:
What I think you need:
Notice the
PARTITION BY. This way you skip every seconddateIdfor eachuserId, 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
WHEREclause in the subquery only works for a single user,PARTITION BYworks for any number of users in one query.Is that it? Is it?
They should give me "detective" badge for this.
Seriously.