I am interested in accomplishing the following: I have two tables from which I need to select a total of 20 patients from a combination of two patient categories:
I need UP TO the first five examples of CATEGORY A from the first table, let's say surgical patients (may be anywhere from 0 to 5) I need the remainder (20-n) to come from CATEGORY B from the second table, let's say patients of any other type.
I have no problem accomplishing this by SELECT TOP 5 from table A and SELECT TOP 15 from table B and using UNION but this only works if I have 5 or more patients in Category A. What I would really like to do is store a count of rows returned in my first query and then using SELECT TOP (20-n) from the second query but I am unsure of how to get this to work. Can anyone help with this syntax/logic? The below is not working because I'm not sure how to declare a variable and use a table alias AND use a union or if this is even possible. Thanks!
(SELECT TOP 5
pata.patid "ID"
, min(zcenc.NAME) "ENCOUNTER TYPE"
FROM TABLEA pata
LEFT JOIN ENCOUNTER zcenc
ON pata.pat_id = zcenc.pat_id
WHERE ......
GROUP BY ....) sqa
UNION
(declare @n as int
set n = count(*)
FROM sqa;
(SELECT TOP (20-n)
patb.patid "ID"
, min(zcenc.NAME) "ENCOUNTER TYPE"
FROM TABLEA patb
LEFT JOIN ENCOUNTER zcenc
ON patb.pat_id = zcenc.pat_id
WHERE ......
GROUP BY ....)
)