使用相同日期对数据进行分组

时间:2014-03-21 22:56:32

标签: sql-server

我有这种情况试图从一个员工历史表中获取信息,该表具有相同员工ID的重复日期

CREATE TABLE EmployeeHIST
(
 Id INT PRIMARY KEY,
 EmployeeId INT,
 EmployeeType INT
 ModifiedDate DATETIME
)

INSERT INTO EmployeeHIST VALUES (1, 1, 'A', '2013-01-24 23:45:12')
INSERT INTO EmployeeHIST VALUES (2, 1, 'A', '2013-02-24 15:45:12')
INSERT INTO EmployeeHIST VALUES (3, 1, 'B', '2013-02-24 15:45:12')

INSERT INTO EmployeeHIST VALUES (4, 2, 'A', '2013-02-24 15:45:12')

INSERT INTO EmployeeHIST VALUES (5, 3, 'B', '2013-02-24 15:45:12')
INSERT INTO EmployeeHIST VALUES (6, 3, 'C', '2013-03-26 12:25:11')


;With CTE AS
(
    SELECT [EmployeeId], [EmployeeType], MAX([ModifiedDate]) AS ModifiedDate
      FROM EmployeeHIST  
     GROUP BY [EmployeeId], [EmployeeType]
)
SELECT E.[EmployeeId], E.[EmployeeType], E.[ModifiedDate]  
  FROM [CTE] E
 INNER JOIN (SELECT [EmployeeId], MAX([ModifiedDate]) AS ModifiedDate
               FROM CTE M
              GROUP BY [EmployeeId]) B
    ON E.[EmployeeId] = B.[EmployeeId]   
   AND E.[ModifiedDate] = B.[ModifiedDate]

一切都是正确的,除了EmployeeId = 1,类型从A变为B但日期是相同的所以我只需要带一条记录,如何修改我的CTE以便能够支持这种类型的问题摆在桌面上?

1 个答案:

答案 0 :(得分:0)

我猜你可以简单地使用像这样的row_number()函数......

;WITH CTE
AS
 (
  SELECT EmployeeId, EmployeeType, ModifiedDate ,
     ROW_NUMBER() OVER (PARTITION BY EmployeeId ORDER BY ModifiedDate DESC ,EmployeeType DESC) AS RN
  FROM EmployeeHIST 
 )
SELECT EmployeeId, EmployeeType, ModifiedDate
FROM CTE
WHERE RN = 1

结果集

╔════════════╦══════════════╦═════════════════════════╗
║ EmployeeId ║ EmployeeType ║      ModifiedDate       ║
╠════════════╬══════════════╬═════════════════════════╣
║          1 ║ B            ║ 2013-02-24 15:45:12.000 ║
║          2 ║ A            ║ 2013-02-24 15:45:12.000 ║
║          3 ║ C            ║ 2013-03-26 12:25:11.000 ║
╚════════════╩══════════════╩═════════════════════════╝