两个表SQL Server 2008上的一列不同

时间:2015-01-14 20:47:13

标签: sql sql-server database 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

1 个答案:

答案 0 :(得分:0)

假设更高的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