I cannot come up with a valid SQL Query for my problem, which I will describe in the scenario of a Blog. I have three tables: User, Blog – for blog entries, and UserStatus which holds the users' status he is assigned.
The tables look like that:
User
ID | Name
Blog
ID | User_ID | Date | Text
UserStatus
ID | User_ID | Valid_From_Date | Status
I guess you can imagine what entries of User and Blog would look like. Here is how UserStatus could look for one user:
ID | User_ID | Valid_From_Date | Status
34 | 7 | 2012-01-01 | Basic
35 | 7 | 2013-04-01 | Premium
36 | 7 | 2014-08-01 | Gold
The user's valid status at a certain date is the most recent one which satisfies Valid_From_Date<=Date. So on '2014-03-30' the valid status of this user is 'Premium'.
Now, what I want is to get all blog entries together with the users' names and valid status.
I have this approach:
SELECT User.Name, UserStatus.Status, Blog.Date, Blog.Text
FROM Blog
JOIN User ON User.ID = Blog.User_ID
JOIN UserStatus ON User.ID = UserStatus.User_ID
JOIN (Select User_ID, max(Valid_From_Date) AS date_for_most_recent_status FROM UserStatus
WHERE date_for_most_recent_status <= ??? GROUP BY User_ID) AS recent_user_status
ON recent_user_status.User_ID = UserStatus.User_ID
AND date_for_most_recent_status = UserStatus.Valid_From_Date
??? -> Can I relate to the particular Blog.Date of current entry when joining?
And that approach:
SELECT User.Name, UserStatus.Status, Blog.Date, Blog.Text, max(Valid_From)
FROM Blog
JOIN User ON User.ID = Blog.User_ID
JOIN UserStatus ON User.ID = UserStatus.User_ID
WHERE UserStatus.Valid_From_Date <= Blog.Date
GROUP BY Blog.Date, User.Name, Blog.Text
Here the good thing is that I can relate to the actual Blog.Date since it is just on Select-Statement. However, I don't know how to handle UserStatus.Status, which should be in the GROUP BY expression but cannot be, since I just want the most recent one.
Can anyone help me out here, please?