1

我有一种情况,我需要根据某个列值 (如下所示)对申请人进行分组并找到该组的计数。当前,查询仅返回计数大于 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
4

2 回答 2

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。

于 2013-02-04T06:49:10.410 回答
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]
于 2013-02-04T09:10:49.463 回答