在一个查询中获取不同子句的计数

时间:2012-01-05 19:12:43

标签: sql sql-server sql-server-2005

是否有更有效率或更好的实践来获得计数而不是我在下面做的事情?

select
   i.org_id,
   o.Org_Name_1,
   count(*) as 'Total Users',
   SUM(CASE WHEN i.email is NULL THEN 1 ELSE 0 END) as 'No Email'
from
   individu i,
   organiz o
where
   i.org_id = o.org_id
group by
   i.org_id, o.Org_Name_1
order by
   count(*) desc

1 个答案:

答案 0 :(得分:6)

SUM(CASE WHEN i.email is NULL THEN 1 ELSE 0 END) as 'No Email'

可以替换为因为... 引自MSDN Count(Transact SQL)

  

COUNT(ALL表达式)计算组中每一行的表达式,并返回非空值的数量。

当表达式放在COUNT语句的括号中时,它将仅计算并计算该字段中的非空值。因此,如果取Count(*) - Count(字段),则得到所有空字段的总和。

COUNT(*) - COUNT(i.email) AS 'No Email'

您的查询将如下所示:

SELECT
   i.org_id,
   o.Org_Name_1,
   COUNT(*) AS 'Total Users',
   COUNT(*) - COUNT(i.email) AS 'No Email'
FROM
   individu i,
   organiz o
WHERE
   i.org_id = o.org_id
GROUP BY
   i.org_id, o.Org_Name_1
ORDER BY
   COUNT(*) DESC