SQL Server 2008 - 从连接表中获取最新记录

时间:2010-05-10 15:58:08

标签: sql-server

我有一个SQL Server 2008数据库。该数据库有两个名为Customer和Order的表。这些表定义如下:

Customer
--------
ID,
First Name,
Last Name

Order
-----
ID,
CustomerID,
Date,
Description

我正在尝试编写一个返回数据库中所有客户的查询。如果用户至少下了一个订单,我想返回与最近下订单相关的信息。目前,我有以下内容:

SELECT
  *
FROM
  Customer c LEFT OUTER JOIN Order o ON c.[ID]=o.[CustomerID]

您可以想象,这将返回与客户相关的所有订单。但实际上,我只想要最新的一个。我如何在SQL中执行此操作?

谢谢!

5 个答案:

答案 0 :(得分:6)

这是一种不假设订单日期是唯一的方法:

SELECT
    Customer.ID CustomerID,
    Customer.FirstName,
    Customer.LastName,
    T1.ID OrderID,
    T1.Date OrderDate,
    T1.Description OrderDescription
FROM Customer
LEFT JOIN (
    SELECT
        *,
        ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY Date DESC) AS rn
    FROM [Order]
) T1
ON Customer.ID = T1.CustomerID AND T1.rn = 1

结果:

CustomerID  FirstName   LastName   OrderID  OrderDate   OrderDescription  
1           FirstName1  LastName1  2        2010-05-02  Description2      
2           FirstName2  LastName2  3        2010-05-03  Description3      
3           FirstName3  LastName3  NULL     NULL        NULL              

测试数据:

CREATE TABLE Customer (ID INT NOT NULL, FirstName VARCHAR(100) NOT NULL, LastName VARCHAR(100) NOT NULL);
INSERT INTO Customer (ID, FirstName, LastName) VALUES
(1, 'FirstName1', 'LastName1'),
(2, 'FirstName2', 'LastName2'),
(3, 'FirstName3', 'LastName3');

CREATE TABLE [Order] (ID INT NOT NULL, CustomerID INT NOT NULL, Date DATE NOT NULL, Description NVARCHAR(100) NOT NULL);
INSERT INTO [Order] (ID, CustomerID, Date, Description) VALUES
(1, 1, '2010-05-01', 'Description1'),
(2, 1, '2010-05-02', 'Description2'),
(3, 2, '2010-05-03', 'Description3'),
(4, 2, '2010-05-03', 'Description4');

答案 1 :(得分:1)

select c.ID, c.FirstName, c.LastName, o.ID as OrderID, o.Date, o.Description
from Customer c 
left outer join (
    select CustomerID, max(Date) as MaxDate
    from Order
    group by CustomerID
) om on c.ID = om.CustomerID 
left outer join Order o on om.CustomerID = o.CustomerID and om.MaxDate = o.Date

答案 2 :(得分:0)

Select * from 
Customer C Left join 
(
    Select o.CustomerID, Description, Date from 
    Orders o inner join
    (
        Select CustomerID, Max(Date) as LastOrder
        From Orders Group by CustomerID
    ) SubLatest on o.CustomerID = SubLatest.CustomerID
    and o.Date = SubLatest.LastOrder 
    ) SubDetails 
on C.id = SubDetails.CustomerID

答案 3 :(得分:0)

我会使用带有Max()函数的where子句来保证最新添加的记录:

(你的代码......) 其中o.id = max(o.id)

答案 4 :(得分:-1)

我希望不是家庭作业! :O)

Select  Top 1  C.*
              ,O.*
From    Customer C left outer join
        Order O on O.CustomerId = C.Id
Order by O.[Date] Desc

希望有所帮助