首页 > 解决方案 > 对表格中的数据进行分类并根据结果进行计数

问题描述

是否可以用表格对数据进行分类并计算它出现的次数?

例如,我正在尝试提取一个查询,该查询将生命数据分类为:1-9 生命、10-49 生命、50-199 生命……等等,然后计算符合这些条件的客户数量?

所以我希望它显示如下。

Lives Category | Number of Clients
1-9 Lives  | 10
10-49 Lives  | 20
50-199 Lives  | 4

到目前为止,我已经创建了这个查询

        SELECT COUNT(CASE WHEN t1.clean_ft_ee_cnt > 0 and t1.clean_ft_ee_cnt < 10 then 1 ELSE NULL END) as "1-9 Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt > 9 and t1.clean_ft_ee_cnt < 50 then 1 ELSE NULL END) as "10-49 Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt > 49 and t1.clean_ft_ee_cnt < 200 then 1 ELSE NULL END) as "50-199 Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt > 199 and t1.clean_ft_ee_cnt < 500 then 1 ELSE NULL END) as "200-499 Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt > 499 and t1.clean_ft_ee_cnt < 2000 then 1 ELSE NULL END) as "500-1,999 Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt > 1999 then 1 ELSE NULL END) as "2,000+ Lives",
        COUNT(CASE when t1.clean_ft_ee_cnt = 0 or t1.clean_ft_ee_cnt is NULL then 1 ELSE NULL END) as "Unknown Lives",
        count(t1.clean_ft_ee_cnt) as "Total Clients"
        FROM [GrpReposUserDev1_dv].[mvpGA].[mvp_client_data_t] t1

这确实有效,但是它在不同的列中水平显示。

标签: sqlcount

解决方案


由于您在此处提供的绑定条件看起来几乎是静态的,我们可以创建一个派生表,该表使用 T-SQLtable value constructor为基表指定多行:

select 
       BT.Lives_Category ,
       count(CT.clean_ft_ee_cnt) as Number_of_Clients
from @mvp_client_data_t CT
join
             --base table here
 (
             select * from 
             (values ('1-9',1,9),
                     ('10-49',10,49),
                     ('50-199',50,199)
             )
             as Base_Table (Lives_Category,MinCnt,MaxCnt)
 ) BT    
 on CT.clean_ft_ee_cnt between BT.MinCnt and BT.MaxCnt
 group by BT.Lives_Category

示例代码在这里..


推荐阅读