小编典典

检索每个客户的最新记录

sql

我有此数据:

ID   NAME   DATE
3    JOHN   2011-08-08
2    YOKO   2010-07-07
1    JOHN   2009-06-06

代码(对于SQL Server 2005):

DECLARE @TESTABLE TABLE (id int, name char(4), date smalldatetime) 
INSERT INTO @TESTABLE VALUES (3, 'JOHN', '2011-08-08')
INSERT INTO @TESTABLE VALUES (2, 'YOKO', '2010-07-07')
INSERT INTO @TESTABLE VALUES (1, 'JOHN', '2009-06-06')

我想为每个名称获取具有最新DATE的ID。像这样:

3    JOHN   2011-08-08
2    YOKO   2010-07-07

实现此目的最优雅的方法是什么?


阅读 137

收藏
2021-03-23

共1个答案

小编典典

;WITH x AS 
(
    SELECT ID, NAME, [DATE], 
      rn = ROW_NUMBER() OVER 
      (PARTITION BY NAME ORDER BY [DATE] DESC)
    FROM @TESTABLE
)
SELECT ID, NAME, [DATE] FROM x WHERE rn = 1
  ORDER BY [DATE] DESC;

尽量避免使用保留字(和模糊的列名),例如[DATE]

2021-03-23