简体   繁体   English

SQL 服务器-根据条件从查询结果集中排除记录

[英]SQL Server - Exclude records from query result set based on condition

Using the below query i am trying to get Average number of FTE Students in each department, Total Students in each department divided by Total FTE students in that department.使用下面的查询,我试图获得每个部门的 FTE 学生平均人数,每个部门的学生总数除以该部门的 FTE 学生总数。

In few departments there will be no FTE students and for that i used case statement to consider average as 0 in that case there are no FTE students (CASE U.[IsFTEStudent] WHEN 1 THEN 1 END)=0 THEN 0在少数部门中不会有 FTE 学生,为此我使用案例陈述将平均值视为 0 在这种情况下没有 FTE 学生(CASE U.[IsFTEStudent] WHEN 1 THEN 1 END)=0 THEN 0

SELECT D.[DepartmentId],
    CASE WHEN COUNT(CASE U.[IsFTEStudent] WHEN 1 THEN 1 END)=0 THEN 0
    ELSE COUNT(S.[StudentId])/COUNT(CASE U.[IsFTEStudent] WHEN 1 THEN 1 END) END AS 'AverageOfFTEStudents'
    FROM dbo.[Student] S
    INNER JOIN [dbo].User U
    ON S.[StudentId] = U.[UserId]
    INNER JOIN dbo.[Department] D
    ON D.DepartmentId = S.[DepartmentId]
    WHERE D.CollegeId = 5
    GROUP BY S.DepartmentId

The above query gives result even with average 0, now i want to exclude those departments who have average of 0 FTE Students, which means there are no FTE students.上面的查询给出了平均为 0 的结果,现在我想排除那些 FTE 学生平均为 0 的部门,这意味着没有 FTE 学生。

In short the departments which have 'AverageOfFTEStudents' as 0 should be excluded from my result简而言之,我的结果中应排除“AverageOfFTEStudents”为 0 的部门

I think you want a having clause;我想你想要一个having子句; and you can simplify the computation logic with AVG() :您可以使用AVG()简化计算逻辑:

SELECT S.[DepartmentId],
    AVG(CASE WHEN [IsFTEStudent] = 1 THEN 1.0 ELSE 0 END) AS [AverageOfFTEStudents]
FROM dbo.[Student] S
INNER JOIN [dbo].User U ON ON S.[StudentId] = U.[UserId]
INNER JOIN dbo.[Department] D ON D.DepartmentId = S.[DepartmentId]
WHERE D.CollegeId = 5
GROUP BY S.DepartmentId
HAVING SUM(CASE WHEN [IsFTEStudent] = 1 THEN 1 ELSE 0 END) > 0

Depending on the actual datatype and values of IsFTEStudent , we might be able to simplify the aggregate expressions a little.根据IsFTEStudent的实际数据类型和值,我们或许可以稍微简化聚合表达式。 If it's an integer with 0 / 1 values for example, then:例如,如果它是一个 integer 和0 / 1值,那么:

SELECT S.[DepartmentId],
    AVG([IsFTEStudent] * 1.0) AS [AverageOfFTEStudents]
FROM dbo.[Student] S
INNER JOIN [dbo].User U ON ON S.[StudentId] = U.[UserId]
INNER JOIN dbo.[Department] D ON D.DepartmentId = S.[DepartmentId]
WHERE D.CollegeId = 5
GROUP BY S.DepartmentId
HAVING SUM([IsFTEStudent]) > 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM