如何编写SQL查询以按工资范围对员工进行分组?

时间:2015-03-09 16:35:38

标签: sql database

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

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

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

可能的查询代码是什么?

表格如下:共有七个表格

  1. REGIONSREGION_ID, REGION_NAME

  2. COUNTRIESCOUNTRY_ID, COUNTRY_NAME, REGION_ID

  3. LOCATIONSLOCATION_ID, STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID

  4. DEPARTMENTSDEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID

  5. EMPLOYEESEMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID, DEPARTMENT_ID

  6. JOB_HISTORYEMPLOYEE_ID, START_DATE, END_DATE, JOB_ID, DEPARTMENT_ID

  7. JOBSJOB_ID, JOB_TITLE, MIN_SALARY, MAX_SALARY

3 个答案:

答案 0 :(得分:1)

您将使用案例陈述来执行此操作。有点像:

SELECT
    CASE 
        WHEN salary BETWEEN 0 and 5000 THEN 'Group1'
        WHEN salary BETWEEN 5001 and 10000 THEN 'Group2'
        ... and on and on ...
        END as PayGroup
FROM
    <yourtable>

在冒险进一步冒险之前阅读基本的T-SQL命令可能是一个好主意,因为这就像SQL 101领域一样。

答案 1 :(得分:1)

您能否提供一些有关您正在使用的数据库架构的详细信息?

  • 确实存在哪些表格
  • 他们有哪些栏目

我假设您想要输出

第1组:xx员工 第2组:yy员工

这是正确的吗? 好吧,这应该是它:

select 
    case
        when salary BETWEEN 0 and 5000 then "Group 1"
        when salary BETWEEN 5001 and 50000 then "Group 2"
        when salary BETWEEN 50001 and 500000 then "Group 3"
    end as salary_group, count(*) as employees_count
from employes group by salary_group

您当然可以更改号码和群组名称!

答案 2 :(得分:-1)

以下代码可以解决您的问题:

create table #temp
(
  EmpName nchar(10),
  EmpSal nchar(10)
)
insert into #temp(EmpName, EmpSal)
(select  
    EmpName,
        case
        when [EmpSalary] BETWEEN 0 and 5000 then 'Group1'
        when [EmpSalary] BETWEEN 5001 and 10000 then 'Group2'
        when [EmpSalary] BETWEEN 10001 and 15000 then 'Group3'
        when [EmpSalary] between 15001 and 20000 then 'Group4'
        end as [EmpSalary] 
     from [dbo].[Employee])

     select EmpSal, count(*) as 'Group by Salary Range' from #temp
     group by EmpSal

请根据您的要求更改列类型。