1

我在 SQL Server 中有一个类似于此的表:

Emp#        CourseID        DateComplete        Status
1           Course1         21/05/2012          Failed
1           Course1         22/05/2012          Passed
2           Course2         22/05/2012          Passed
3           Course3         22/05/2012          Passed
4           Course1         31/01/2012          Failed
4           Course1         28/02/2012          Passed
4           Course2         28/02/2012          Passed

尝试为每个 emp# 捕获每个课程的最新记录。如果在同一天尝试了相同的课程,则捕获“通过”课程记录。

沿着这些思路思考:

SELECT DISTINCT .....
        INTO Dup_Table
        FROM MainTable
GROUP BY ........
HAVING COUNT(*) > 1

DELETE MainTable
        WHERE Emp# IN (SELECT Emp# FROM Dup_Table)

INSERT MainTable SELECT * FROM Dup_Table

Drop Table Dup_Table
GO

但不确定这是不是

  1. 最好的方法和
  2. 如何将 Emp#/courseID/DateComplete/Status 放在一起。
4

2 回答 2

7
;WITH cte 
     AS (SELECT Row_number() OVER (partition BY EMPID, courseid ORDER BY 
                DateComplete 
                DESC, 
                status DESC) RN 
         FROM   MainTable) 
DELETE FROM cte 
WHERE  RN > 1 
于 2012-05-21T10:33:22.447 回答
2

您可以使用row_number()按分区和按范围排序来获取最后一条记录

Select *
From  (
    Select *,
           Row_Number() Over (Partition By Emp#, CourseID Order By DateComplete DESC, Case When Status = 'Passed' Then 1 Else 2 End  ) AS RecordNumber
    From #Emp)Z
Where Z.RecordNumber = 1
于 2012-05-21T11:39:28.397 回答