按组列出的SQL总计数
我有疑问按组列出的SQL总计数,sql,sql-server,tsql,group-by,case,Sql,Sql Server,Tsql,Group By,Case,我有疑问 SELECT count(hh.[HouseholdIncome]) CountHH, hh.[HouseholdIncome] , case when try_convert(numeric(20), hh.[HouseholdIncome]) between 0 and 4012 then 'ERDC Group 2' when try_convert(numeric(20), hh.[HouseholdIncome]) b
SELECT
count(hh.[HouseholdIncome]) CountHH, hh.[HouseholdIncome]
, case
when try_convert(numeric(20), hh.[HouseholdIncome]) between 0 and 4012 then 'ERDC Group 2'
when try_convert(numeric(20), hh.[HouseholdIncome]) between 4013 and 4956 then 'ERDC Group 3'
when try_convert(numeric(20), hh.[HouseholdIncome]) between 4957 and 5899 then 'ERDC Group 4'
end as IncomeGroup
FROM [MergeData].[dbo].[Contact] c
join [MergeData].[dbo].[HouseholdIncome] hh on c.ContactID = hh.ContactID
group by hh.[HouseholdIncome]
order by IncomeGroup asc
我想对Incomegroup进行分组计数(第2组、第3组等的总数)。如果我正确地跟随了您,您可以使用cte、子查询或
交叉应用
第三种选择是:
select x.IncomeGroup, count(*) cnt
from MergeData.dbo.Contact c
inner join MergeData.dbo.HouseholdIncome hh on c.ContactID = hh.ContactID
cross apply (values(
case
when try_convert(numeric(20), hh.HouseholdIncome) between 0 and 4012 then 'ERDC Group 2'
when try_convert(numeric(20), hh.HouseholdIncome) between 4013 and 4956 then 'ERDC Group 3'
when try_convert(numeric(20), hh.HouseholdIncome) between 4957 and 5899 then 'ERDC Group 4'
end)
) x(IncomeGroup)
group by x.IncomeGroup
order by x.IncomeGroup
您可以在sum函数中使用case
SELECT
count(hh.[HouseholdIncome]) CountHH, hh.[HouseholdIncome]
,sum(case when try_convert(numeric(20), hh.[HouseholdIncome]) between 0 and 4012 then hh.[HouseholdIncome] else 0 end) as 'ERDC Group 2',
sum(case when try_convert(numeric(20), hh.[HouseholdIncome]) between 4013 and 4956 then hh.[HouseholdIncome] else 0 end) as 'ERDC Group3',
sum(case when try_convert(numeric(20), hh.[HouseholdIncome]) between 4957 and 5899 then hh.[HouseholdIncome] else 0 end) as 'ERDC Group 4'
FROM [MergeData].[dbo].[Contact] c
join [MergeData].[dbo].[HouseholdIncome] hh on c.ContactID = hh.ContactID
group by hh.[HouseholdIncome]
order by IncomeGroup asc
请提供样本数据和预期结果