在 SQL 服务器中除以计数 (*)

Divide count by count(*) in SQL Server

这是我的查询:

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

是否可以通过别名来划分字段? :

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

我在SQL服务器上用不了,请问有什么办法吗?谢谢

不幸的是,您不能像 Sql 服务器那样使用 alias;你必须重复这个表达。您可以(正如您已经发现和其他人发布的那样)使用 subquery/cte/join 等到 return 具有该别名的列并像那样使用它,但这就是 column/expression 的名字,不是别名。

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_null
from table t

此外,将 +.0 添加到除法方程的任一侧以避免整数除法(returning 0 而不是 0.dddd 作为百分比)。

好的,我自己找到了:

SELECT nb_null/total from(
   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
) as req

而不是

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

您可以使用

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

我会这样写:

select Count(*) as total,
       avg(case when t.id is null then 1.0 else 0 end) as nb_null,
       count(t.id) as nb_not_null
from table t;

COUNT(<col>)的定义是统计非NULL值;你可能会很好地使用内置函数。

但是,为什么一个名为 id 的专栏可能是 NULL,这超出了我的理解范围。应该声明为 NOT NULL.

我需要用任意数量的特征(不仅仅是空与非空)来解决类似的问题,我还希望将它们转换为百分比。这可能对您或有类似问题的其他人有帮助:

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 pct
FROM counts
ORDER BY pct DESC