简体   繁体   中英

SQl server query multiple aggregate columns

I need to write a query in sql server to data get like this.

ry

Essentially it is group by dept, race, gender and then

SUM(employees_of_race_by_gender),Sum(employees_Of_Dept).

I could get data of first four columns, getting sum of employees in that dept is becoming difficult. Could you pls help me in writing the query?

All these details in same table Emp. Columns of Emp are Emp_Number, Race_Name,Gender,Dept

Your "num_of_emp_in_race" is actually by Gender too

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

You should probably have this

    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

Edit: the DISTINCT appears to be applied before the COUNT (which would odd based on this ) so try this instead

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

Since the two sums you're looking for are based on a different aggregation, you need to calculate them separately and join the result. In such cases I first build the selects to show me the different results, making it easy to catch errors early:

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

Afterwards, joining those two is pretty straight forward:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM