retrieve the most recent record for each customer

别等时光非礼了梦想. 提交于 2019-12-09 00:16:13

问题


I have this data:

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

Code (for 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')

I want to get, for each NAME, the ID that has the most recent DATE. Like this:

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

What is the most elegant way of accomplishing this?


回答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;

Try to avoid reserved words (and vague column names) like [DATE]...




回答2:


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



回答3:


below is a possible solution:

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


来源:https://stackoverflow.com/questions/7473336/retrieve-the-most-recent-record-for-each-customer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!