Divide count by count(*) in SQL Server

Vincent Ducroquet picture Vincent Ducroquet · Apr 13, 2017 · Viewed 21.7k times · Source

Here is my query :

SELECT 
    COUNT(*) AS total,
    COUNT(CASE WHEN t.id IS NULL THEN 1 END) AS nb_null,
    COUNT(CASE WHEN t.id IS NOT NULL THEN 1 END) AS nb_not_null
FROM
    table t

Is it possible to divide a field by an alias? :

SELECT 
    COUNT(*) AS total,
    COUNT(CASE WHEN t.id IS NULL THEN 1 END) / total AS nb_null,
    COUNT(CASE WHEN t.id IS NOT NULL THEN 1 END) AS nb_not_null
FROM
    table t

It doesn't work for me in SQL Server, I'd like to know if there is any way to do this? Thanks

Answer

Martin Smith picture Martin Smith · Apr 13, 2017

Instead of

COUNT(CASE WHEN t.id is null THEN 1 END)/Count(*) 

You can use

AVG(CASE WHEN t.id is null THEN 1.0 ELSE 0 END)