Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MS SQL Query to find all User IDs that worked all specified dates

I have a table designed as this (simple example):

WorkRecords (UserID, DateWorked)

    UserID       DateWorked    
-----------   -----------------   
111111        '2023/09/01'
222222        '2023/09/01'
333333        '2023/09/02'
222222        '2023/09/02'
111111        '2023/09/02'
333333        '2023/09/01'
111111        '2023/09/03'

I need to query the table and return the UserIDs of every person that worked all specified dates (in real usage I am querying over a 20-day date range). In this example if I wanted to know the ID of who worked 9/1 and 9/2 and 9/3 (user 111111), what is the most efficient way to do so?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Possibly an easy way, but it eludes me. The current way I am doing it is using a CTE of each date and doing multiple UNIONs but it’s an extremely taxing query.

>Solution :

You can achieve this by using queries with a GROUP BY and HAVING clause to filter the results based on the specified dates. for example:

SELECT UserID    
FROM WorkRecords    
WHERE DateWorked IN ('2023-09-01', '2023-09-02', '2023-09-03')    
GROUP BY UserID    
HAVING COUNT(DISTINCT DateWorked) = 3; -- Adjust the count based on the number of dates you're checking
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading