In my SQL database, I have a CLIENTS table with an ID column. I have an APPOINTMENTS table containing ID, CLIENTID (which is the ID from the CLIENTS table), and STATUS.
Is there a way to write one SELECT statement that will find the client ID of the client whose STATUS='NO SHOW' the most often? Is there a way to display all clients and ORDER BY how often that an appointment exists where STATUS='NO SHOW'?
Removing the unnecessary join from TomC's answer :
select * from (
select CLIENTID, count(*) as NoShow
from APPOINTMENTS
WHERE STATUS='NO SHOW'
group by CLIENTID
) q order by NoShow desc
select C.ID,A.STATUS from CLIENTS C
INNER JOIN APPOINEMENTS A ON A.CLIENTID = C.ID
WHERE STATUS='NO SHOW'
Do you mean like this ? Hope this help you
Need to count the number of appointments, and order by that list. Beyond that you can do what you want.
select * from (
select C.ID, count(*) as NoShow
from CLIENTS C
INNER JOIN APPOINEMENTS A ON A.CLIENTID = C.ID
WHERE STATUS='NO SHOW'
group by c.ID
) q order by NoShow desc
If you want "the most often", then you want to limit the result to one row. The ANSI/ISO SQL construct is fetch first 1 row only
:
select CLIENTID
from APPOINTMENTS
where STATUS = 'NO SHOW'
group by CLIENTID
order by count(*) desc
fetch first 1 row only;
Some databases use limit
or select top (1)
instead of fetch first
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.