如何通过一个查询从单个列中获取多个COUNT个?

时间:2010-12-13 20:38:20

标签: sql sql-server sql-server-2005

在我写的一个应用程序中,我有很多查询似乎应该是一个...但我无法弄清楚如何去做。

以下是一个示例:

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)

然后我有四个相同的其他查询,只是在最后一行中包含的LevelID不同。我基本上可以根据他们提供的年级水平获得入学人数和学校数量。

请记住,我不仅需要结果(我可以简单地UNION这些查询),我需要知道哪个数字是哪个。

感谢您的任何建议。

Russell Schutte

1 个答案:

答案 0 :(得分:7)

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

或者您可以使用GROUP BY LevelId然后在收到查询后添加结果;它可能更容易使用,如果这是一个选项:

SELECT LevelID, Count(*) FROM Schools GROUP BY LevelID

编辑在sum语句中将enrollment替换为1,以更好地反映原始查询返回的结果。