Suppose I have a single table foo, with relevant columns flag, date and username.
I am struggling to come up with a PostgreSQL query that does the following:
Select all rows where...
dateis later than a specific date- and
flag = 0 - and there is NO other row of a later
dateand withflag = 1for the same user
...grouped by username.
The problem is very much the third requirement in the list above. I have tried building the query using subqueries with EXCEPT, WHERE NOT EXISTS, WITH and LATERAL, but I always run into a dead end when the dates of the subqueries must be compared to each other and I cannot reference them.
Is this possible within a single SQL statement?