2011-11-30 89 views
0

我需要在sql server中寫一個查詢來獲取數據。SQl服務器查詢多個聚合列

qry

本質上,它是由部門,種族,性別組,然後

SUM(employees_of_race_by_gender),Sum(employees_Of_Dept). 

我能得到前四列的數據,讓員工的總和的部門變得困難。 你能幫我寫下查詢嗎?

所有這些細節在同一張表Emp。電磁脈衝列Emp_Number,Race_Name,性別,部門

+0

我不瞭解你的'num_of_emp_in_race'數字來自哪裏?當數據中有4個匹配行時,爲什麼'Latin'在'1'和'2'之間波動? –

+0

@馬丁史密斯:它是按性別分類的我估計 – gbn

+0

你能指定你的結果嗎,你在找什麼結果集 –

回答

6

你 「num_of_emp_in_race」 實際上是性別太

SELECT DISTINCT 
    Dept, 
    Race_name, 
    Gender, 
    COUNT(*) OVER (PARTITION BY Dept, Race_name, Gender) AS num_of_emp_in_race, 
    COUNT(*) OVER (PARTITION BY Dept) AS num_of_emp_dept 
FROM 
    MyTable 

你或許應該有這種

COUNT(*) OVER (PARTITION BY Dept, Gender) AS PerDeptRace 
    COUNT(*) OVER (PARTITION BY Dept, Race_name) AS PerDeptGender, 
    COUNT(*) OVER (PARTITION BY Dept, Race_name, Gender) AS PerDeptRaceGender, 
    COUNT(*) OVER (PARTITION BY Dept) AS PerDept 

編輯:DISTINCT似乎是在COUNT之前應用(其中would odd based on this)所以試試這個代替

SELECT DISTINCT 
    * 
FROM 
    (
    SELECT 
     Dept, 
     Race_name, 
     Gender, 
     COUNT(*) OVER (PARTITION BY Dept, Race_name, Gender) AS num_of_emp_in_race, 
     COUNT(*) OVER (PARTITION BY Dept) AS num_of_emp_dept 
    FROM 
     MyTable 
    ) foo 
+0

COUNT(*)OVER(按部門劃分)由於num_of_emp_dept未給出屬於部門的員工總數。而是給出部門總數。例如:在輸出圖像中,「執行」部門的最後一列的值爲3,但HR部門的值爲3。 – crazyTechie

+0

@abhishek:將更新 – gbn

1

由於您正在尋找的兩種總和基於不同的聚合,因此您需要分別計算它們並加入結果。在這種情況下,我先建選擇給我看不同的結果,因此很容易發現錯誤早期:

SELECT Dept, Gender, race_name, COUNT(*) as num_of_emp_in_race 
FROM Emp 
GROUP BY 1, 2, 3 

SELECT Dept, COUNT(*) as num_of_emp_in_dept 
FROM Emp 
GROUP BY 1 

之後,加入這兩個是非常直截了當:

SELECT * 
FROM (first statement here) as by_race 
JOIN (second statement here) as by_dept ON (by_race.Dept = by_dept.Dept)