SQL общее количество по группам - PullRequest
0 голосов
/ 09 мая 2020

У меня есть запрос

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 и т. Д.).

Ответы [ 2 ]

1 голос
/ 09 мая 2020

Вы можете использовать функцию 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
0 голосов
/ 09 мая 2020

Если я правильно следил за вами, вы можете использовать cte, подзапрос или cross apply.

Третий вариант:

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
...