获取连接表中的最后一条记录

时间:2013-01-21 13:21:38

标签: sql sql-server select greatest-n-per-group

我在这里有一个问题,我不理解有关该主题的帖子。所以这是我的问题:

在我的申请中,我有以下实体:

Customer( CustomerId int, Name varchar(200), Email varchar(100), ...)
Employee (EmployeeId int, Name varchar(200), Email varchar(100), ...)
Sale(SaleId int, CustomerId int, EmployeeId int, SaleDate datetime, ...) Join Table

我怎样才能获得表中每位客户的最后一次销售?

示例(示例数据):

Customer:
    1, John Smith, jonh@smith.com, ...
    2, Michael Jackson, michael@jackson.com, ...
    3, Bill Clinton, bill@clinton.com, ...

Employee:
   1, Steve Jobs, steve@jobs.com, ...
   2, Bill Gates, bill@gates.com, ...
   3, Mark Zuckerberg, mark@zuckerberg.com, ...

Sales:
   1, 1 (John Smith), 1 (Steve Jobs), '2013-01-02'
   2, 1 (John Smith), 2 (Bill Gates), '2013-01-11'
   3, 1 (John Smith), 3 (Mark Zuckerberg), '2012-12-25'
   4, 2 (Michael Jackson), 2 (Bill Gates), '2012-11-02'
   5, 2 (Michael Jackson), 1 (Steve Jobs), '2013-01-13'
   6, 3 (Bill Clinton), 3 (Mark Zuckerberg), '2013-01-17'
   7, 3 (Bill Clinton), 2 (Bill Gates), '2011-12-20'

我的结果查询必须带来以下结果:

   2, 1 (John Smith), 2 (Bill Gates), '2013-01-11'
   5, 2 (Michael Jackson), 1 (Steve Jobs), '2013-01-13'
   6, 3 (Bill Clinton), 3 (Mark Zuckerberg), '2013-01-17'

1 个答案:

答案 0 :(得分:1)

由于您已提及使用SQL Server,因此请使用Common Table ExpressionWindow Function

WITH latestRecords
AS
(
    SELECT  SaleId , CustomerId, EmployeeId , SaleDate,
            DENSE_RANK() OVER (PARTITION BY CustomerId
                                ORDER BY SaleDate DESC) RN
    FROM    Sale
)
SELECT  a.SaleId,
        b.Name AS CustomerName,
        c.Name as EmployeeName,
        a.SaleDate
FROM    latestRecords a
        INNER JOIN Customer b
            ON a.CustomerID = b.CustomerID
        INNER JOIN Employee c
            ON a.EmployeeID = c.EmployeeID
WHERE   a.RN = 1