区分两个表上的一列 SQL Server 2008

Distinct one column on two tables SQL Server 2008

我有两个不同的表,我只想在一列上使用 distinct。我只想获取最近的记录。我应该在 SQL Server 2008 中编写什么查询?我只想使用不同的 CustomerID 而不是任何其他列。

表 1:Customer
列:CustomerID, CustomerName

表 2:Order
列:OrderID, CustomerID, OrderName

我尝试了两个 SQL 查询都不起作用

第一次查询

select Distinct on (CustomerID) CustomerID, CustomerName, OrderID, OrderName
from Customer
left join Order on Customer.CustomerID = Order.CustomerID

第二次查询:

select Max(Distinct ID) 
    CustomerID, CustomerName, OrderID, OrderName
from
    Customer 
left join 
    Order on Customer.CustomerID = Order.CustomerID

假设较高的 OrderID 是最新的,如果我正确理解您的要求,这应该可行:

select
    c.CustomerID,
    c.CustomerName,
    o.OrderID,
    o.OrderName
from Customer as c
    inner join (select
                    CustomerID,
                    max(update_date) as max_update_date
                from Customer
                group by CustomerID) as mc
        on mc.CustomerID = c.CustomerID
        and mc.max_update_date = c.update_date
    inner join Order as o
        on o.CustomerID = c.CustomerID
    inner join (select
                    CustomerID,
                    max(OrderID) as max_OrderID
                from Order
                group by CustomerID) as m
        on m.CustomerID = c.CustomerID
        and m.max_OrderID = o.OrderID