SQL Query根据年龄范围返回数据

时间:2015-11-02 20:53:18

标签: sql sql-server range aggregate-functions

我有员工表,其中包含一些数据,如下图所示,我想查询它以查找每个年龄段的员工平均工资和百分比。我使用了以下查询,但我不知道如何包含avarage和百分比结果。请帮忙。

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

3 个答案:

答案 0 :(得分:0)

您可以使用cte创建年龄组,加入任何其他包含您想要使用的信息的表格,例如LoanBalance或Salary。

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 

答案 1 :(得分: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

答案 2 :(得分:0)

不需要连接,平均值是一个简单的SQL AVG,可以使用GROUP SUM轻松计算百分比:

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