我该怎么写这个查询?

时间:2014-06-25 23:08:42

标签: sql

我有一个包含Employee_Id,Effective_Date,Salary列的表。也就是说,对于每个员工,我根据工资变化的时间有多条记录。现在我想为每个员工打印最新的effective_date工资。怎么做?

6 个答案:

答案 0 :(得分:2)

select Employee_Id, Effective_Date, Salary
from employees T
where not exists
    (select 1 from employees TT where TT.Employee_Id = T.Employee_Id and TT.Effective_Date > T.Effective_Date)

这可能有用吗?

答案 1 :(得分:1)

SELECT  T.Employee_Id
       ,T.Effective_Date
       ,T.Salary
FROM TableName T INNER JOIN (
                             SELECT Employee_Id
                                    ,MAX(Effective_Date) Last_Date
                             FROM TableName
                             GROUP BY Employee_Id
                             ) LT
ON T.Employee_Id = LT.Employee_Id 
AND T.Effective_Date = LT.Last_Date

Sql Server 2005及更高版本

SELECT Employee_Id, Effective_Date, Salary
FROM (
     SELECT Employee_Id, Effective_Date, Salary
        ,ROW_NUMBER() OVER (PARTITION BY Employee_Id ORDER BY Effective_Date DESC) RN
     FROM TableName
     )A
WHERE RN = 1

答案 2 :(得分:0)

select Employee_Id, Effective_Date, Salary
from employees T
where not exists
    (select 1 from employees TT where TT.Employee_Id = T.Employee_Id and TT.Effective_Date > T.Effective_Date)

答案 3 :(得分:0)

以下查询适合您:

SELECT * FROM Your_Table_Name_Here 
GROUP BY Employee_Id ORDER BY Effective_Date DESC LIMIT 1

答案 4 :(得分:0)

假设您的表名是" Employee_Salary_Table",您可以试试这个:

SELECT
    salaries.Employee_ID,
    salaries.Effective_Date,
    salaries.Salary
FROM
    (
    SELECT
        Employee_ID,
        Effective_Date,
        Salary,
        RANK() OVER ( PARTITION BY  Employee_ID
                      ORDER BY      Effective_Date DESC ) N
     FROM
         Employee_Salary_Table
     ) salaries
 WHERE
     salaries.N = 1

内部选择按日期(从最新开始)对所有员工工资条目进行排名。外部选择采用等级为1(最新)的这些值。

答案 5 :(得分:0)

由于您没有指定数据库,我为POSTGRES提供了解决方案

 SELECT DISTINCT ON (Employee_Id) Employee_Id, Effective_Date, Salary
   FROM TableName 
   ORDER BY Effective_Date DESC