retrieve the most recent record for each customer

前端 未结 3 1252
梦如初夏
梦如初夏 2021-01-03 13:53

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

相关标签:
3条回答
  • 2021-01-03 13:56

    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
    
    0 讨论(0)
  • 2021-01-03 13:57
    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
    
    0 讨论(0)
  • 2021-01-03 14:18
    ;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]...

    0 讨论(0)
提交回复
热议问题