示例代码:
DECLARE @TABLE TABLE (ID int, Name varchar(50), Date Datetime2)
INSERT INTO @TABLE (ID, Name, Date)
SELECT 1, 'abc', GETDATE()
UNION ALL
SELECT 1, 'def', GETDATE()
UNION ALL
SELECT 1, 'hij', GETDATE()
UNION ALL
SELECT 1, 'abc', GETDATE()-2
UNION ALL
SELECT 1, 'def', GETDATE()-2
UNION ALL
SELECT 1, 'hij', GETDATE()-2
UNION ALL
SELECT 1, 'abc', GETDATE()-4
UNION ALL
SELECT 1, 'def', GETDATE()-4
UNION ALL
SELECT 1, 'hij', GETDATE()-4
UNION ALL
SELECT 2, 'abc', GETDATE()-1
UNION ALL
SELECT 2, 'def', GETDATE()-1
UNION ALL
SELECT 2, 'hij', GETDATE()-1
UNION ALL
SELECT 2, 'abc', GETDATE()-3
UNION ALL
SELECT 2, 'def', GETDATE()-3
UNION ALL
SELECT 2, 'hij', GETDATE()-3
UNION ALL
SELECT 2, 'abc', GETDATE()-4
UNION ALL
SELECT 2, 'def', GETDATE()-4
UNION ALL
SELECT 2, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()+2
UNION ALL
SELECT 3, 'def', GETDATE()+2
UNION ALL
SELECT 3, 'hij', GETDATE()+2
UNION ALL
SELECT 3, 'abc', GETDATE()-4
UNION ALL
SELECT 3, 'def', GETDATE()-4
UNION ALL
SELECT 3, 'hij', GETDATE()-4
UNION ALL
SELECT 3, 'abc', GETDATE()-5
UNION ALL
SELECT 3, 'def', GETDATE()-5
UNION ALL
SELECT 3, 'hij', GETDATE()-5
UNION ALL
SELECT 4, 'abc', GETDATE()+1
UNION ALL
SELECT 4, 'def', GETDATE()+1
UNION ALL
SELECT 4, 'hij', GETDATE()+1
UNION ALL
SELECT 4, 'abc', GETDATE()-4
UNION ALL
SELECT 4, 'def', GETDATE()-4
UNION ALL
SELECT 4, 'hij', GETDATE()-4
UNION ALL
SELECT 4, 'abc', GETDATE()-5
UNION ALL
SELECT 4, 'def', GETDATE()-5
UNION ALL
SELECT 4, 'hij', GETDATE()-5
SELECT * FROM @TABLE
我想要的数据输出反映了以下记录的输出
3 abc 2013-09-18
3 def 2013-09-18
3 hij 2013-09-18
描述:我想查询最近处理的 ID/Name 的数据(Max(Date))(如果在同一日期/时间处理,可以有多个 ID)
我的尝试...
SELECT DISTINCT A.*, B.My_Rank
FROM @TABLE A
INNER JOIN
(
SELECT DISTINCT ID, Name, CONVERT(varchar(8), Date, 101) AS Date, RANK() OVER (PARTITION BY ID, Name ORDER BY CONVERT(varchar(8), Date, 101) DESC) My_Rank, MAX(CONVERT(varchar(8), Date, 101)) OVER (partition by ID, Name) Max_Date
FROM @TABLE
GROUP BY ID, Name, CONVERT(varchar(8), Date, 101)
) B
ON A.ID = B.ID AND CONVERT(varchar(8), A.Date, 101) = B.Max_Date
WHERE My_Rank = 1
显然,这个逻辑是行不通的。“我想根据最新处理的 ID/姓名获取 ID/姓名/日期的记录。
谢谢