In an application I've written, I have lots of queries that it seems should be one... but I can't figure out how to do it.
Here's a sample:
SELECT SUM(enrollment) AS SchoolEnrollment, COUNT(institutionID) AS NumberOfSchools
FROM Schools
WHERE LevelID IN (4,5,6,7,8,14,15,16,20)
SELECT SUM(enrollment) AS SchoolEnrollment, COUNT(institutionID) AS NumberOfSchools
FROM Schools
WHERE LevelID IN (10,11)
Then I have four additional queries that are identical, only differing in the LevelID's that are INcluded in the last line. I'm basically getting a sum of enrollments and number of schools, based on the grade levels they offer.
Keep in mind that I not开发者_如何学Go only need the results (I could simply UNION these queries), I need to know which number is which.
Thanks for any advice.
Russell Schutte
SELECT SUM (case
when LevelID IN (4,5,6,7,8,14,15,16,20) then enrollment
else 0
end) as firstEnrollmentCount,
COUNT (case
when LevelID IN (4,5,6,7,8,14,15,16,20) then 1
else 0
end) as firstNumberOfInstitutions,
SUM (case
when LevelID IN (10, 11) then enrollment
else 0
end) as secondEnrollmentCount,
COUNT (case
when LevelID IN (10, 11) then 1
else 0
end) as secondNumberOfInstitutions,
FROM Schools
Or you could just use GROUP BY LevelId
and then add up your results after you get the query back; it might be easier to work with, if that's an option:
SELECT LevelID, Count(*) FROM Schools GROUP BY LevelID
EDIT Replaced 1 with enrollment
in the sum statement to better reflect the results gotten back by the original queries.
精彩评论