2015-11-02 181 views
0

我在员工表中添加了一些数据,因为我在下面的图片中附加了这些数据,并且想要查询它以查找每个年龄段的平均工资和员工百分比。我已经使用了下面的查询,但我不知道如何包含avarage和百分比结果。请任何帮助。返回基于年龄范围的数据的SQL查询

SELECT emp.agerange as [age Range], count(emp.agerange) as [Number of employee on this age range] 
FROM (
    SELECT CASE 
    WHEN age >60 THEN '60 And Up' 
    WHEN age >=41 and age <=60 THEN '41-60' 
    WHEN age >=21 and age <=40 THEN '21-40' 
    WHEN age <=20 THEN '20 And Below' END as agerange 
    from kin.dbo.Employee) emp 
    group by emp.agerange 

Table and result I want

回答

0

你可以使用一个CTE来创建你的年龄组,与信息你要使用的任何其他表,如LoanBalance或薪水加盟。

WITH emp as (
     SELECT CASE 
     WHEN age >60 THEN '60 And Up' 
     WHEN age >=41 and age <=60 THEN '41-60' 
     WHEN age >=21 and age <=40 THEN '21-40' 
     WHEN age <=20 THEN '20 And Below' END as agerange 
     ,l.LoanBalance -- might not be the field you are looking for 
     from kin.dbo.Employee 
     left join Loan l 
     on ??????) -- You decide the join condition between these two tables 

SELECT emp.agerange as [age Range] 
,count(*) as [Number of employee on this age range] 
,count(*)/(SELECT COUNT(*) FROM emp) as pctAgeRange 
,(SELECT SUM(LoanBalance)/COUNT(*) FROM emp) as avgLoanBalance 
FROM emp 
    group by emp.agerange 
+0

我只有一个表(employee),我可以得到的结果没有使用左连接? –

+0

@ Jhon.M是的,只要确保你在'emp'中包含任何你想要计算的字段。' –

0

这工作?我把你的AgeRange函数放入CTE中。

WITH cteRange AS (
    SELECT ID, 
     CASE 
      WHEN age > 60 THEN '60 And Up' 
      WHEN age >= 41 and age <=60 THEN '41-60' 
      WHEN age >= 21 and age <=40 THEN '21-40' 
      WHEN age <= 20 THEN '20 And Below' 
     END AS 'ageRange' 
    FROM kin.dbo.Employee 
) 
SELECT cteRange.ageRange, 
    COUNT(*) AS 'Number of Employees', 
    SUM(emp.Salary) AS 'Total Salary', 
    AVG(emp.Salary) AS 'Average Salary', 
    ROUND(COUNT(*)/(SELECT COUNT(*) FROM kin.dbo.Employee)*100,2) AS '% Employees in age Range' 
FROM kin.dbo.Employee AS emp 
    INNER JOIN cteRange ON emp.ID = cteRange.ID 
GROUP BY cteRange.ageRange 
+0

平均工资只适用于年龄范围,它不必计算整个数据平均值。 –

+0

它只是在年龄范围,COUNT(*)'按底部的年龄范围分组。 COUNT(*)'只是选择组中每一行的简短手段。 – EMUEVIL

0

无需连接,一般是一个简单的SQL AVG并可以很容易地使用一组总和来计算的百分比:

SELECT emp.agerange as [age Range], 
    count(*) as [Number of employee on this age range], 
    SUM(Salary) AS "Total Salary", 
    AVG(Salary) AS "Average Salary", 
    100 * COUNT(*)/SUM(COUNT(*)) OVER() AS "% of employees in this range" 
FROM 
(
    SELECT Salary, 
    CASE 
     WHEN age >60 THEN '60 And Up' 
     WHEN age >=41 and age <=60 THEN '41-60' 
     WHEN age >=21 and age <=40 THEN '21-40' 
     WHEN age <=20 THEN '20 And Below' 
    END as agerange 
    from kin.dbo.Employee 
) emp 
group by emp.agerange