Divide count by count(*) in SQL Server Divide count by count(*) in SQL Server sql-server sql-server

Divide count by count(*) in SQL Server


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)


I needed to solve a similar problem with an arbitrary number of features (not just null versus non-null), and I also wanted them converted to percentages. This may be helpful for you or someone else with a similar question:

WITH counts AS   (SELECT [feature],   COUNT(*) AS cnt  FROM [your_table]  GROUP BY [feature])SELECT [feature], CAST(100 * num AS DOUBLE) / (SELECT SUM(num) FROM counts)   AS pctFROM countsORDER BY pct DESC


Unfortunately you can not use an alias like that in Sql Server; you have to repeat the expression. You can (as you have already found and others have posted) use a subquery/cte/join etc to return a column with that alias and use it like that, but that is then the column/expression's name, not an alias.

SELECT Count(*) as total,count(CASE WHEN t.id is null THEN 1 END)/(Count(*)+.0)  as nb_null,COUNT(CASE WHEN t.id is not null THEN 1 END) as nb_not_nullfrom table t

Also, add +.0 to either side of your division equation to avoid integer division (returning 0 instead of 0.dddd for percent).