2014-02-08 39 views
-1

如何在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 

數據我想我必須使用樞軸聲明,但我不知道需要一些幫助在這

+1

太好了。你有什麼問題?你使用什麼數據? –

+0

我使用輸入數據更新了問題 – javanoob

+0

也許,「pivot」和/或「dynamic pivot」是您要搜索的術語。 –

回答

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

+0

@javanoob這解決您的問題? –

+0

嗨,這是有用的,但你可以請讓我知道是否有一個例如城市的列,我們需要在每個城市的僱員人數..非常感謝您的回答 – javanoob

+0

城市進入你的問題?爲了解決你需要的問題,你必須在桌面上有任何城市的鏈接或數據。只用department_id和工資是不可能的。 –

1
Hi please go through the following example, Might be it will help you. 

如果您正在使用Oracle10g的是這種格式, 如果11克旋轉功能是有

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 
+0

你能告訴我如何添加城市也查詢,我修改了我的問題 – javanoob