I have a system where users can complete two types of tests. I need to get a list of DISTINCT users sorted by the date of their latest test completion.
For this purpose the tables may as well be set out as:
Test_Users
- Test_User_Id (int)
Test_1_Results
- Test_1_Result_Id (int)
- Test_User_Id (int)
- Date_Of_Completion (datetime)
Test_2_Results
- Test_2_Result_Id (int)
- Test_User_Id (int)
- Date_Of_Completion (datetime)
I can happily get a list of all the different Test_User_Id‘s using a UNION as follows:
SELECT Test_User_Id FROM Test_1_Results
UNION
SELECT Test_User_Id FROM Test_2_Results
And I could easily sort the results from one of these tables using a ORDER BY Date_Of_Completion DESC but i do not know how to do this with the UNION or if this is even the best way to proceed.
Ultimately i would like to be able to wrap this query within others like:
SELECT *
FROM Test_Users
WHERE Test_User_Id IN (
//The query i am asking about
)
WHERE some_criteria
But so far i haven’t had any luck doing this while using a UNION and i am not sure what i am doing wrong.
The reason i am trying to do this is that the admin user needs to be able to view a list of everyone who has completed their tests with the most recent completions at the top.
I am fairly familiar with SQL, but i have never really had to use the UNION operator before.
This should work