hungrykoala hungrykoala - 4 months ago 6
SQL Question

How to query specific rows per date and per user?

I have this table:

user | date
1 | 2016-08-10
1 | 2016-09-10
1 | 2016-10-10
2 | 2016-08-15
2 | 2016-08-18
2 | 2016-08-19


What I want to do here is to get the specific user for every date. For example, I want to get the users where date >= 2016-08-12. My expected result would be:

user | date
1 | 2016-09-10
2 | 2016-08-15


I would note that these dates are actual date and different users have different dates with them, thus in this example, the values of date2 for the two users will be different.

Will anyone be able to help me formulate a proper query for this?

Thank you

Answer

You can try this query.

SELECT 
T.user,
MIN(T.date) AS min_date
FROM your_table T
WHERE T.date >= '2016-08-12'
GROUP BY T.user;

SQL FIDDLE DEMO

Note: This query picks the first date that is greater than the input date for each user.

Comments