是否可以使用表对数据进行分类并计算发生的次数?
例如,我正在尝试通过以下方式提取对生活数据进行分类的查询:1-9个生活,10-49个生活,50-199个生活..etc,然后计算符合这些条件的客户数量? / p>
所以我希望它显示如下。
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
这确实有效,但是它在不同的列中水平显示。
答案 0 :(得分:0)
由于您在此处提供的绑定条件似乎是静态的,因此我们可以创建一个派生表,该派生表使用T-SQL table 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