我有一张表EmployeeDetails
DeptID | workDate | percentage
------------------------------------------
1 06/07/16 10:10:10 10%
1 07/07/16 11:11:10 20%
2 06/07/16 09:10:10 5%
2 07/07/16 08:10:10 3%
3 06/07/16 10:10:10 15%
4 07/07/16 11:10:10 20%
你能不能帮我找一个sql查询来查找' workDate'的最大日期时间。然后根据' workDate'获得每个部门的相应记录。
预期产出:
DeptID | workDate | percentage
1 07/07/16 11:11:10 20%
2 07/07/16 08:10:10 3%
3 06/07/16 10:10:10 15%
4 07/07/16 11:10:10 20%
非常感谢。
答案 0 :(得分:0)
请参阅下文。在这种情况下,内部联接将有所帮助。
CREATE TABLE #EmployeeDetails
(
DeptID int
,workDate datetime
,percentage varchar(100)
)
INSERT INTO #EmployeeDetails
SELECT 1,'06/07/16 10:10:10','10%'
UNION
SELECT 1,'07/07/16 11:11:10','20%'
UNION
SELECT 2,'06/07/16 09:10:10','5%'
UNION
SELECT 2,'07/07/16 08:10:10','3%'
UNION
SELECT 3,'06/07/16 10:10:10','15%'
UNION
SELECT 4,'07/07/16 11:10:10','20%'
SELECT T1.*
FROM #EmployeeDetails T1
JOIN (SELECT DeptID,MAX(workDate) AS max_workdate
From #EmployeeDetails
GROUP BY DeptID) T2
ON T1.DeptID = T2.DeptID AND T1.workDate = T2.max_workdate
ORDER BY T1.DeptID