2015-11-02 180 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