我需要在sql server中编写一个查询数据就像这样。
基本上它是由部门,种族,性别分组然后
SUM(employees_of_race_by_gender),Sum(employees_Of_Dept).
我可以获得前四列的数据,获得该部门的员工总数变得越来越困难。 你能帮我写一下这个问题吗?
所有这些细节在同一张表中。 Emp的列是Emp_Number,Race_Name,Gender,Dept
答案 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
答案 1 :(得分: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)