COUNT和WHERE语句查询

时间:2012-06-02 12:14:28

标签: sql sql-server-2008

目前我有这个

SELECT
    COUNT (enrollment_id) AS enrollments,
    COUNT (result) AS 
    MAX (result) AS highest_result,
    AVG (result) AS average_result,
    MIN (period_code) AS earliest_enrollment    
FROM 
    enrollment
WHERE
result IS NULL  

我想要的是总数中的注册人数,这是COUNT(enrollment_id)的用途。然后,我想计算结果列中的NULL值的数量,以获得unfinalised_enrollments的列。

底部的WHERE子句是否会影响使用结果列的其他SELECT语句?如果是这样,我如何制作它,以便我只能计算结果列中NULL值的数量,并将其显示在名为unfinalised_enrollment的列中。

提前感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用SUM代替COUNT

SELECT
    COUNT (enrollment_id) AS enrollments,
    SUM (CASE WHEN result IS NULL THEN 1 ELSE 0 END) AS null_results,
    MAX (result) AS highest_result,
    AVG (result) AS average_result,
    MIN (period_code) AS earliest_enrollment    
FROM enrollment    

答案 1 :(得分:0)

这个应该完成你想要的:

SELECT
    COUNT (enrollment_id) AS enrollments,
    ( SELECT COUNT (result) FROM enrollment WHERE result IS NULL ) AS unfinalised_enrollment,
    MAX (result) AS highest_result,
    AVG (result) AS average_result,
    MIN (period_code) AS earliest_enrollment    
FROM 
    enrollment;

答案 2 :(得分:0)

您可以使用:

SELECT
    COUNT (enrollment_id) AS enrollments,
    Count(*) - Count(result) AS null_results,
    MAX (result) AS highest_result,
    AVG (result) AS average_result,
    MIN (period_code) AS earliest_enrollment    
FROM enrollment   

Count(*)将计算总行数,Count(result)enter code here将计算结果不为null的行总数