我正在学习数据库查询,并希望从Oracle数据库中的HR Schema中找到以下SQL查询。
查找每个薪资组中的员工数量。薪资组被视为如下。
组1:0k至< 5K,5k至< 10k,10k至< 15k,等等。
可能的查询代码是什么?
表格如下:共有七个表格
REGIONS
:REGION_ID, REGION_NAME
COUNTRIES
:COUNTRY_ID, COUNTRY_NAME, REGION_ID
LOCATIONS
:LOCATION_ID, STREET_ADDRESS, POSTAL_CODE, CITY, STATE_PROVINCE, COUNTRY_ID
DEPARTMENTS
:DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID
EMPLOYEES
: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
答案 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
请根据您的要求更改列类型。