Count number of people in each country in SQL server 2008
I have two tables:
Table 1:
------------------------------
|Country |Emp Level |Name|
|-----------|-----------|-----
|UK |Staff |A
|US |Admin Staff|B
|CA |Staff |C
|NL |Admin Staff|D
|MN |Intern |E
|IN |Staff |F
|UK |Staff |G
|US |Admin Staff|H
------------------------------
Table 2:
---------------------------------------------
|Level Guid |Level name |Country code |
|-----------|-----------|-------------------|
|101 |Admin Staff|UK |
|102 |Admin Staff|US |
|103 |Admin Staff|Global |
|105 |Staff |UK |
|106 |Staff |US |
|107 |Staff |Global |
|108 |Intern |UK |
|109 |Intern |US |
|110 |Intern |Global |
---------------------------------------------
And result should be:
|Level ID |Level |Country| Count |
|105 |Staff |UK | 2 |
|102 |Admin Staff|US | 2 |
|107 |Staff |CA | 1 |
|103 |Admin Staff|NL | 1 |
|110 |Intern |MN | 1 |
|107 |Staff |IN | 1 |
In table 2 any country except US,Uk is considered Global. Note that the
countries are counted sepeartely even though in Table 2, all the countries
except US, Uk are Global. I have tried a query liek this but it is giving
me error More than 1 value returned in subquery
select country, emp-Levels,COUNT(emp-Levels) count
,
"LevelID"=
CASE
When
(select Level_Guid from table_2 T
where u.emp-Levels=T.Level_name
and u.country in ('UK','US')) IS not null
then (select Level_guid from table_2 T
where u.emp-Levels=T.level_name
and u.country not in ('UK', 'US')
)
ELSE
(select Level_guid from [DPN_Reporting].dbo.TaxonomyTermSet T
where u.emp_Levels=T.level_name
and T.level_name='Global')
end
from table_1 u
where emp-Levels is not null AND emp-Levels !=''
group by emp-Levels,country
order by COUNT(emp-Levels) desc
No comments:
Post a Comment