sql query group by语句建议

时间:2015-03-09 20:03:25

标签: sql database

我正在学习数据库查询,并希望从Oracle数据库中的HR Schema中找到以下SQL查询。

查找每个薪资组中的员工数量。薪资组被视为如下。

组1:0k至< 5K,5k至< 10k,10k至< 15k,等等。

可能的查询代码是什么?

表格如下:共有七个表格

地区:REGION_ID,REGION_NAME

COUNTRIES:COUNTRY_ID,COUNTRY_NAME,REGION_ID

地点:LOCATION_ID,STREET_ADDRESS,POSTAL_CODE,CITY,STATE_PROVINCE,COUNTRY_ID

部门:DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID

员工:EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

JOB_HISTORY:EMPLOYEE_ID,START_DATE,END_DATE,JOB_ID,DEPARTMENT_ID

JOBS:JOB_ID,JOB_TITLE,MIN_SALARY,MAX_SALARY

2 个答案:

答案 0 :(得分:0)

我首先使用公用表表达式(CTE)来使用case语句计算不同的组...

WITH CTE AS (
SELECT Emp_ID, 
            case when salary >= 0 salary < 5000 then "<5K"
            when salary >= 5000 and salary < 10000 then "<10k"
            when salary >= 10000 and salary < 15000 then "<15k"
            else "UDF" end as SalaryGroup
FROM Employees)

SELECT count(Emp_ID) as Cnt, SalaryGroup
FROM CTE
GROUP BY SalaryGroup;

然后,我从该表中选择,以计算工资组的计数。

答案 1 :(得分:-1)

select trunc(salary/5000,00) e,
       count(*) 
from EMPLOYEES 
group by trunc(SALARY/5000,0) 
ORDER by e asc