Check whether value exists in column for each group

You can filter SQL groups with the HAVING clause. For example, you can group your table by users and their activity, and then filter it to contain only those that have completed the tutorial:

SELECT user FROM tbl
GROUP BY user, activity
HAVING activity = 'completed_tutorial';

EDIT: After OP has edited their question, this is my new answer. Here, I assume that your table has a date field.

SELECT *, COALESCE(date >= (
    SELECT date FROM tbl WHERE activity = 'completed_tutorial'
    AND user = outertbl.user
), FALSE)
FROM tbl AS outertbl
ORDER BY date

Notice, that such query is essentially N² when unoptimised, so I would recommend instead to just get the data from the database and then process it in your program.


I am not sure about the speed of this, but what about the following solution?

SELECT
    user
    ,max(CASE
            WHEN activity = "completed_tutorial" THEN 1
            ELSE 0
            END) AS completed_tutorial
  FROM tbl
  GROUP BY user
 ;

Tags:

Sql

Postgresql