在case语句中检查所有组的计数

时间:2013-02-04 06:40:38

标签: sql tsql

我有一种情况需要根据某些列值对申请人进行分组 (如下所示)并找到该组的计数。 目前,查询仅返回计数大于0的列。

应该对查询进行哪些修改,以便它显示所有组及其计数为零?

查询:

select Applicant_info.range as [Income Range], count(*) as [Total Students],order_number =
          CASE range
             WHEN 'Did not specify' THEN '1'
             WHEN '0-25000' THEN '2'
             WHEN '25001-50000' THEN '3'
             WHEN '50001-75000' THEN '4'
             WHEN '75001-100000' THEN '5'
             WHEN '100001-200000' THEN '6'
             WHEN '200000 and Above' THEN '7'
          END
    from (
      select case  
        when Annual_Income is null or Annual_Income = '' then 'Did not specify' 
        when Annual_Income between 0 and 25000 then '0-25000'
        when Annual_Income between 25001 and 50000 then '25001-50000'
        when Annual_Income between 50001 and 75000 then '50001-75000'
        when Annual_Income between 75001 and 100000 then '75001-100000'
        when Annual_Income between 100001 and 200000 then '100001-200000'
        when Annual_Income > 200000 then '200000 and Above'
        end as range
      from Applicant_info)Applicant_info
    group by Applicant_info.range
    order by order_number

2 个答案:

答案 0 :(得分:2)

为每个表达式使用单独的CASE表达式,如下所示:

Select 
  range as [Income Range], 
  SUM(CASE when Annual_Income is null or Annual_Income = '' then END) AS 'Did not specify',
  SUM(CASE when Annual_Income between 0 and 25000 then 1 ELSE 0 END) AS '0-25000',
  SUM(CASE when Annual_Income between 25001 and 50000 then 1 ELSE 0 END) AS '25001-50000',
  SUM(CASE when Annual_Income between 50001 and 75000 then 1 ELSE 0END) AS  '50001-75000',
  SUM(CASE when Annual_Income between 75001 and 100000 then 1 ELSE 0 END) AS  '75001-100000',
  SUM(CASE when Annual_Income between 100001 and 200000 then 1 ELSE 0END) AS  '100001-200000',
  SUM(CASE when Annual_Income > 200000 then 1 ELSE 0 END) AS  '200000 and Above'
from Applicant_info
GROUP BY range;

请注意:SUM函数实际上是一个计数,因为它总和为0或1.

答案 1 :(得分:1)

您可以使用外部联接和查找表来确保即使计数为零也包括所有范围。

SELECT C.[Range], COUNT(B.[Income_Band]) AS [Count]
FROM Applicant_info
CROSS APPLY
(
    SELECT
        CASE
            WHEN Annual_Income IS NULL OR ISNUMERIC(Annual_Income) = 0 THEN 1
            WHEN Annual_Income > 200000 THEN 7
            WHEN Annual_Income > 100000 THEN 6
            WHEN Annual_Income > 75000  THEN 5
            WHEN Annual_Income > 50000  THEN 4
            WHEN Annual_Income > 25000  THEN 3
            WHEN Annual_Income >= 0  THEN 2
            ELSE 1
        END AS [Income_Band]
) B
RIGHT JOIN
(
    SELECT 1 AS [Income_Band], 'Did not specify' AS [Range]
    UNION SELECT 2, '0-25000'
    UNION ALL SELECT 3, '25001-50000'
    UNION ALL SELECT 4, '50001-75000'
    UNION ALL SELECT 5, '75001-100000'
    UNION ALL SELECT 6, '100001-200000'
    UNION ALL SELECT 7, '200000 and Above'
) C
    ON C.[Income_Band] = B.[Income_Band]
GROUP BY C.[Range], C.[Income_Band]
ORDER BY C.[Income_Band]