In a PostgreSQL database, I have an extract of cases worked in any given month by all of the case handlers. I need to randomly select 4 cases per case handler to complete a check. Is there any way to do this in SQL?
Assuming the database is called casemanagement
and the table is called cases
, I would expect the query to obtain the full extract without the random sample to be something along the lines of:
SELECT a.case_id, a.case_handler, a.case_status
FROM casemanagement.cases a
WHERE a.case_status = 'Completed'
ORDER BY a.case_id;
If I were to add in a condition for a random sample with a limit, I assume the following would work for an individual case handler:
SELECT a.case_id, a.case_handler, a.case_status
FROM casemanagement.cases a
WHERE a.case_status = 'Completed' and a.case_handler = 'John Smith'
ORDER BY RANDOM()
LIMIT 4
But is it possible to have the limit of 4 without having to specify the case handler in the where function?