I am a high school student and am currently working on an exercise about SQL, which is this query that made me stuck for an hour and still couldn’t solve it. The table schema is as follows:
Table
The question my teacher gave me was: How any Students have one or more blood donations in 2016?
Thanks for any generous help.
The SQL I tried to run is
x
SELECT COUNT(*)
FROM DONA
WHERE StudID IN (SELECT StudID
FROM DONA
WHERE YEAR(DonDate)= 2016
GROUP BY StudID
HAVING COUNT(*)>1)
GROUP BY StudID
And I still couldn’t figure out how to COUNT the number of students.
Advertisement
Answer
You can join both the tables and use the keyword DISTINCT to find DISTINCT students-
SELECT COUNT(StudID)
FROM (SELECT DISTINCT StudID
FROM DONA D
WHERE YEAR(DonDate) = 2016) T;