I have two tables in a database. One called Users and one called Days. The Users table has a column called ID which contains some numbers and an ActiveUser column which contains either a 0(not active) or 1(active). The Days table has a column called UserID which contains the same numbers the ID column from the Users table has. It also has a column called Day which contains info like "2015-01-01 00:00:00:000".
Users Table:
ID | ActiveUser
-------------------
10 | 0
11 | 1
12 | 1
13 | 0
Days Table:
User_ID | Day
------------------
10 | 2010-06-24 00:00:00.000
11 | 2011-07-05 00:00:00.000
12 | 2008-06-19 00:00:00.000
13 | 2010-06-20 00:00:00.000
10 | 2009-09-02 00:00:00.000
12 | 2010-08-15 00:00:00.000
11 | 2011-05-06 00:00:00.000
13 | 2012-04-25 00:00:00.000
I'm trying to create a query that finds the most recent Day listed for each Active user. So using the tables above, the query I'm trying to make should give me the following:
Day
------
2011-07-05 00:00:00.000
2010-08-15 00:00:00.000
Which corresponds to the two Active users with user ID's 11 and 12, both of which have two entries for Day, but the query picks the most recent date.
I'm new to SQL, and the closest I've got is below, which doesn't take into account the Users table (also, used https://stackoverflow.com/a/2411703/2480598 as a template):
select Days.Day
from Days
inner join (select User_ID, max(day) as MaxDay
from Days
group by User_ID
) tm on Days.User_ID = tm.User_ID and Days.Day = tm.MaxDay
This gives me the list of dates for users active and non-active.