2015-03-25 21 views
0

數據庫:沒有嵌套選擇計數:這可能嗎?

Department Position    Points 
    A  Manager    50 
    A  Supervisor   10 
    A  Supervisor   10 
    A  Staff     2 
    A  Staff     2 
    B  Manager    40 
    B  SuperVisor   8 
    B  Staff     2 
    B  Staff     2 
    B  Staff     2 

所需的查詢結果:

Dept Manager Count Supervisor Count Staff Count Staff Total Pts 

A  1     2    2     4 
B  1     1    3     4 

是所需的查詢結果可能不使用嵌套選擇與計數?

我們有一個類似的一定的存儲過程使用嵌套計數和我們喜歡更簡單和更好的表現/快

+0

您也可以使用PIVOT查詢此 – 2015-03-25 07:46:37

回答

0

使用Conditional Aggregate來算只有特定的數據

Select Department, 
     count(case when Position = 'Manager' then 1 END) as Manager, 
     count(case when Position = 'Supervisor' then 1 END) as Supervisor, 
     count(case when Position = 'Staff' then 1 END) as Staff 
From yourtable 
Group by Department 

如果你是使用Sql Server使用這種

SELECT Department, 
     Manager, 
     Supervisor, 
     Staff 
FROM Yourtable 
     PIVOT (Count(Position) 
      FOR Position IN (Manager,Supervisor,Staff))pv 
+0

感謝。我添加了一個額外的問題 – 2015-03-26 07:03:21

0

使用條件SUM

SELECT Department, 
     SUM(CASE WHEN Position = 'Manager' THEN 1 END) as Manager, 
     SUM(CASE WHEN Position = 'Supervisor' THEN 1 END) as Supervisor, 
     SUM(CASE WHEN Position = 'Staff' THEN 1 END) as Staff 
FROM yourtable 
GROUP BY Department 
+0

謝謝。我又增加了一個問題 – 2015-03-26 07:03:57

0

或者您可以使用PIVOT操作:

select Detartment, Manager, Supervisor, Staff 
from yourtable 
pivot (count(Position) for Position in (Manager, Supervisor, Staff)) Result