如何使用oracle中的每个薪水显示每个部门的员工人数
类似这样的事情
department_id salar_equal_1000 salar_equal_20000 city_boston city_detroit city_none 10 2 3 2 1 2 20 1 2 1 2 0
表包含这样的数据
department_id salary city 10 1000 boston 10 1000 boston 10 2000 detroit 10 2000 10 2000 20 1000 boston 20 2000 detroit 20 2000 detroit
我想我必须使用pivot声明,但我不确定需要一些帮助
答案 0 :(得分:1)
试试这个:
select
department_id,
sum(case when salary = 1000 then 1 else 0 end) as salar_equal_1000,
sum(case when salary = 2000 then 1 else 0 end) as salar_equal_2000,
sum(case when city = 'boston' then 1 else 0 end) as city_boston,
sum(case when city = 'detroit' then 1 else 0 end) as city_detroit,
sum(case when city is null then 1 else 0 end) as city_none
from
employees
group by department_id
order by department_id
再次编辑:
在这里查看小提琴:http://sqlfiddle.com/#!4/3564c/6
答案 1 :(得分:1)
Hi please go through the following example, Might be it will help you.
如果您正在使用oracle10g,这是格式, 如果有11g枢轴功能
WITH cte(dept_id,salary) AS (SELECT 10,1000 FROM dual
UNION ALL
SELECT 10,1000 FROM dual
UNION ALL
SELECT 10,1000 FROM dual
UNION ALL
SELECT 20,1000 FROM dual
UNION ALL
SELECT 10,2000 FROM dual
UNION ALL
SELECT 10,2000 FROM dual
UNION ALL
SELECT 20,1000 FROM dual
UNION ALL
SELECT 20,2000 FROM dual
UNION ALL
SELECT 20,2000 FROM dual
),
TEMP as(SELECT
dept_id,
count(salary) cnt,salary
FROM
cte
GROUP BY salary, dept_id)
SELECT dept_id,sum(CASE WHEN salary=1000 THEN cnt ELSE 0 END)salary_1000,
sum(CASE WHEN salary=2000 THEN cnt ELSE 0 END) salary_2000 FROM TEMP
GROUP BY dept_id