SQL Server:获取相关表列的Count(),其中有一些条件

时间:2016-12-02 04:15:39

标签: sql sql-server

给出表CollegeMajors

| Id | Major       |
|----|-------------|
| 1  | Accounting  |
| 2  | Math        |
| 3  | Engineering |

EnrolledStudents

| Id | CollegeMajorId | Name            | HasGraduated |
|----|----------------|-----------------|--------------|
| 1  | 1              | Grace Smith     | 1            |
| 2  | 1              | Tony Fabio      | 0            |
| 3  | 1              | Michael Ross    | 1            |
| 4  | 3              | Fletcher Thomas | 1            |
| 5  | 2              | Dwayne Johnson  | 0            |

我想做一个像

这样的查询
Select 
    CollegeMajors.Major,
    Count(select number of students who have graduated) AS TotalGraduated,
    Count(select number of students who have not graduated) AS TotalNotGraduated
From 
    CollegeMajors
Inner Join 
    EnrolledStudents On EnrolledStudents.CollegeMajorId = CollegeMajors.Id

我希望得到这样的结果

| Major       | TotalGraduated | TotalNotGraduated |
|-------------|----------------|-------------------|
| Accounting  | 2              | 1                 |
| Math        | 0              | 1                 |
| Engineering | 1              | 0                 |

所以问题是,COUNT内部有什么类型的查询来实现上述目标?

3 个答案:

答案 0 :(得分:2)

Select CollegeMajors.Major
  , COUNT(CASE WHEN EnrolledStudents.HasGraduated= 0 then 1 ELSE NULL END) as "TotalNotGraduated",
    COUNT(CASE WHEN EnrolledStudents.HasGraduated = 1 then 1 ELSE NULL END) as "TotalGraduated"
From CollegeMajors
InnerJoin EnrolledStudents On EnrolledStudents.CollegeMajorId = CollegeMajors.Id
GROUP BY CollegeMajors.Major

答案 1 :(得分:1)

您可以使用 COUNT 中的 CASE 语句来获得所需的结果。请尝试以下更新的查询。

Select CollegeMajors.Major
  , COUNT(CASE WHEN EnrolledStudents.HasGraduated= 0 then 1 ELSE NULL END) as "TotalNotGraduated",
    COUNT(CASE WHEN EnrolledStudents.HasGraduated = 1 then 1 ELSE NULL END) as "TotalGraduated"
From CollegeMajors
InnerJoin EnrolledStudents On EnrolledStudents.CollegeMajorId = CollegeMajors.Id
GROUP BY CollegeMajors.Major

答案 2 :(得分:0)

您可以尝试使用渐变计数:

Select Count(*) From EnrolledStudents group by CollegeMajorId having HasGraduated = 1

对于没有毕业的人,将1改为零:

Select Count(*) From EnrolledStudents group by CollegeMajorId having HasGraduated = 0