Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按组列出的SQL总计数_Sql_Sql Server_Tsql_Group By_Case - Fatal编程技术网

按组列出的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

请提供样本数据和预期结果