我正在使用SQL 2005进行查询。 我正在尝试获取数字列的最新日期。诀窍是有另一个列(速率)使用列日期,我最后获取错误的列。
一个例子可以更好地解释我的问题。
这是我的SQL表EmployeeRates:
----------------------------------
FkEmployee | Date | Rate | Number |
----------------------------------
1 2000 15 1.5
1 2001 16 1.5
1 2002 16 1.6
2 2000 12 1.5
2 2001 14 1.6
2 2002 15 1.6
因此,如果我获取最新日期,目前我有:
我现在的代码(2015-08-10 14:15)
SELECT t1.FkEmployee, t1.Date
FROM EmployeeRates t1
INNER JOIN
(
SELECT FkEmployee, MAX(Date) AS MaxDate
FROM EmployeeRates
GROUP BY FkEmployee
)
t2 ON t1.FkEmploye = t2.FkEmploye
AND t1.DateTaux = t2.MaxDate
ORDER BY t1.FkEmploye
感谢任何可以帮助的人=)
答案 0 :(得分:0)
这应该有效。首先按员工编号MIN
查找日期,然后获取MAX
。这将确保您获得每个号码的最早日期,但每位员工的最新日期:
SELECT t1.FkEmployee, t1.Date
FROM EmployeeRates t1
INNER JOIN
(SELECT FkEmployee,MAX(MinDate) AS MaxDate from
(SELECT FkEmployee, MIN(Date) AS MinDate
FROM EmployeeRates
GROUP BY FkEmployee,Number) a
GROUP BY Fkemployee
)
t2 ON t1.FkEmployee = t2.FkEmployee
AND t1.DateTaux = t2.MaxDate
ORDER BY t1.FkEmployee