我有一张这样的表:
-------------------------------
EMP ID|Country |Emp Level |
------|-----------|-----------|
102 |UK |Staff |
103 |US |Admin Staff|
104 |CA |Staff |
105 |NL |Admin Staff|
106 |MN |Intern |
107 |IN |Staff |
108 |UK |Staff |
109 |US |Admin Staff|
110 |IN |Admin Staff|
------------------------------
我需要根据以下条件计算每个国家/地区每个类别的员工数量:如果国家/地区不在('UK' or 'US' or 'CA')
,则将其视为“全球”。所以我们的答案应该是:
------------------------------
|Country |Emp Level |Count|
|-----------|-----------|-----
|UK |Staff |2
|US |Admin Staff|2
|CA |Staff |1
|Global |Admin Staff|2
|Global |Intern |1
|Global |Staff |1
到目前为止,我可以计算每个国家/地区的每个类别的工作人员数量,但不能在不在给定的数量和数量范围内的国家/地区进行计算。将它们显示为全局。
答案 0 :(得分:4)
SELECT Country, EmpLevel, COUNT(*) AS Count
FROM my_table
WHERE Country IN ('UK', 'US', 'CA')
GROUP BY Country, EmpLevel
UNION
SELECT 'Global', EmpLevel, COUNT(*) AS Count
FROM my_table
WHERE Country NOT IN ('UK', 'US', 'CA')
GROUP BY EmpLevel
在sqlfiddle上查看。
答案 1 :(得分:2)
你试过这个吗?
select country as cou, emp_level as emp, count(*)
from your_table
where country in ('UK', 'US', 'CA')
group by cou, emp
order by cou, emp
union
select 'global', emp_level as emp, count(*)
from your_table
where country not in ('UK', 'US', 'CA')
group by emp
order by emp
答案 2 :(得分:2)
SELECT
CASE WHEN Country IN ('UK', 'US', 'CA') THEN Country ELSE 'Global' END
AS Country,
EmpLevel,
COUNT(*) AS Count
FROM
tableX
GROUP BY
CASE WHEN Country IN ('UK', 'US', 'CA') THEN Country ELSE 'Global' END,
EmpLevel ;
此查询与@eggyal和@duffymo之间的结果会有所不同 - 如果列NULL
中有Country
行。此查询将计算'Global'
组中的这些行,另一个查询将根本不计算它们。
答案 3 :(得分:1)
也许这样的事情会起作用(未经测试,可能需要更多的工作)
SELECT CASE WHEN Country NOT IN ('US','UK','CA') THEN 'Global' ELSE Country, Emp_Level, COUNT(*)
FROM table_name
GROUP BY Country, Emp_Level