检索每个客户的最新记录

时间:2011-09-19 15:27:25

标签: sql sql-server sql-server-2005 tsql greatest-n-per-group

我有这些数据:

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')

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

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

实现这一目标的最优雅方式是什么?

3 个答案:

答案 0 :(得分:14)

;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] ...

答案 1 :(得分:4)

SELECT <fields>
FROM SourceTable st
INNER JOIN (SELECT name, MAX(Datefield) as Datefield
            FROM SourceTable
            GROUP BY name) x
    ON x.Name = st.name
    AND x.datefield = st.datefield

答案 2 :(得分:-1)

以下是可能的解决方案:

Select c.CustomerID, c.CustomerName, c.CustomerOrder, c.CustomerOrderDate, c.CustomerQty
from tblCustomer c
inner join (select c2.CustomerName, MAX(c2.CustomerOrderDate) as MaxDate from tblCustomer c2 group by c2.CustomerName) c2
on c.CustomerName = c2.CustomerName
where c.CustomerOrderDate = c2.MaxDate