获取在发布日期之后获得薪水的员工的详细信息

时间:2016-08-30 14:36:29

标签: sql oracle

我有两张桌子 - EmployeeSalary

员工有3列: EmpId , JoiningDate and LastDate.

薪资表有3列: EmpId, SalaryPerMonth, SalaryDate.

select * from salG;

1   02-FEB-2016 100
2   31-JAN-2016 200
2   28-FEB-2016 200
2   01-APR-2016 200
3   30-JAN-2016 300
3   23-FEB-2016 300
3   29-MAR-2016 300

select * from empG;

1   01-JAN-2016 31-JAN-2016
2   10-JAN-2016 31-MAR-2016
3   11-JAN-2016 31-MAR-2016

我需要获得那些薪水来自最后一天的员工的empId和SalaryPerMonth。

我试过了 -

select emp.id,s.salary 
from empG emp,
salG s
where emp.END_DATE < ( select max(s.sal_date) from salG s where emp.id= s.id); 

但这是笛卡儿的产品。还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

外部查询中根本不需要两个表:

select s.id, s.salary 
from salG s
where s.sal_date > (select e.END_DATE from empg e where e.id = s.id); 

这似乎是对你所要求的更直接的翻译。

答案 1 :(得分:1)

您没有提供样品预期输出,但据我所知,这应该可以满足您的需求。不需要子查询或任何子查询,您可以在连接中执行逻辑;

示例表'员工'

IF OBJECT_ID('tempdb..#Employee') IS NOT NULL DROP TABLE #Employee
CREATE TABLE #Employee (EmpID int, JoiningDate date, LastDate date)
INSERT INTO #Employee
VALUES
(1,'2016-01-01','2016-01-31')
,(2, '2016-01-10','2016-03-31')
,(3, '2016-01-11','2016-03-31')

样本表'薪水'

IF OBJECT_ID('tempdb..#Salary') IS NOT NULL DROP TABLE #Salary
CREATE TABLE #Salary (EmpId int, SalaryPerMonth int, SalaryDate date)
INSERT INTO #Salary
VALUES
 (1, 100, '2016-02-02')
,(2, 200, '2016-01-31')
,(2, 200, '2016-02-28')
,(2, 200, '2016-04-01')
,(3, 300, '2016-01-30')
,(3, 300, '2016-02-23')
,(3, 300, '2016-03-29')

查询

SELECT
    e.EmpID
    ,e.JoiningDate
    ,e.LastDate
    ,s.SalaryDate
    ,s.SalaryPerMonth
FROM #Employee e
INNER JOIN #Salary s
    ON e.EmpID = s.EmpId
    AND e.LastDate < s.SalaryDate

输出

EmpID   JoiningDate LastDate    SalaryDate  SalaryPerMonth
1       2016-01-01  2016-01-31  2016-02-02  100
2       2016-01-10  2016-03-31  2016-04-01  200