如何在SQL表中查找最早的日期

时间:2017-01-14 01:38:42

标签: sql oracle express oracle-apex

我正在进行SQL查询,我需要一些帮助

问题是:
什么是员工当前的工资,他们刚开始工作时的工资是多少? (在开始时给出姓名,首写字母,当前工资,部门名称,开始日期和工资)

问题是:
我不断收到所有日期,我无法知道如何过滤它只显示第一个日期(开始/雇用日期)。
有什么建议吗? 我的SQL代码如下所示:

SELECT M.NAME,
       M.FIRSTLETTERS,
       M.MONTHSALARY,
       D.NAME,
       H.STARTDATE,
       H.SALARY
FROM   E_EMPLOYEES M
       LEFT OUTER JOIN E_DEPARTMENTS A
                    ON M.AFD = A.ANR
       INNER JOIN E_historie H
               ON M.MNR = H.MNR 

2 个答案:

答案 0 :(得分:1)

您可以使用聚合和keep来实现此目的。查询如下所示:

SELECT M.NAME, M.FIRSTLETTERS,
       MIN(H.STARTDATE) as STARTDATE, 
       MAX(H.SALARY) KEEP (DENSE_RANK FIRST ORDER BY H.STARTDATE) as FIRST_SALARY,
       MAX(H.SALARY) KEEP (DENSE_RANK FIRST ORDER BY H.STARTDATE DESC) as LAST_SALARY
FROM E_EMPLOYEES M INNER JOIN
     E_DEPARTMENTS A
     ON M.AFD = A.ANR INNER JOIN
     E_historie H
     ON M.MNR = H.MNR 
GROUP BY M.MNR, M.NAME, M.FIRSTLETTERS;

答案 1 :(得分:1)

使用ROW_NUMBER从历史记录表中查找每位员工的第一个薪水

SELECT M.NAME,
       M.FIRSTLETTERS,
       M.MONTHSALARY, -- considering this is current salary
       A.NAME, -- I think there is a typo here Alias name should be A not H
       H.STARTDATE,
       H.SALARY
FROM   E_EMPLOYEES M
       LEFT OUTER JOIN E_DEPARTMENTS A
                    ON M.AFD = A.ANR
       INNER JOIN (SELECT Row_number()OVER(partition BY H.MNR ORDER BY H.STARTDATE ASC) AS Rn,
                          H.MNR,
                          H.STARTDATE,
                          H.STARTDATE
                   FROM   E_historie H) H
               ON M.MNR = H.MNR
WHERE  Rn = 1