Order ---------------------------- OrderID Product 1 Стакан 2 Журнал 3 Чайник 4 Стакан 5 Ручка
Нужно выбрать самый последний продукт купленный покупателем.
Result --------------------------- CustomerID Product 1 Чайник 2 Ручка
Я написал это вот так: select Customer.CustomerID, Order.Product from Order join (select max(OrderID) Orderid from Customer group by CustomerID) c on Order.Orderid=c.Orderid join Customer on Customer.Orderid=Order.Orderid
Как это написать умнее, чтоб без derived таблицы и побыстрее?
select c.CustomerId, o.Product from Customer c
inner join Order o on o.OrderId = (select max(OrderID) from Customer c1 where c1.CustomerID = c.CustomerId)
The philosophy of one century is the common sense of the next. --Henry Ward Beecher
Order ---------------------------- OrderID Product 1 Стакан 2 Журнал 3 Чайник 4 Стакан 5 Ручка
Нужно выбрать самый последний продукт купленный покупателем.
Result --------------------------- CustomerID Product 1 Чайник 2 Ручка
Я написал это вот так: select Customer.CustomerID, Order.Product from Order join (select max(OrderID) Orderid from Customer group by CustomerID) c on Order.Orderid=c.Orderid join Customer on Customer.Orderid=Order.Orderid
Как это написать умнее, чтоб без derived таблицы и побыстрее?
Your query contains an unecessary extra join. It should be:
select c.CustomerID, Orders.Product from (select CustomerID, max(OrderID) Orderid from Customer group by CustomerID) c join Orders on c.Orderid=Orders.Orderid
'Order' , by the way, is a keyword and Yukon does not allow it.
roadman wrote:select c.CustomerId, o.Product from Customer c inner join Order o on o.OrderId = (select max(OrderID) from Customer c1 where c1.CustomerID = c.CustomerId)
The above query is incorrect as it'll produce duplicates. It should be :
select c.CustomerID, o.Product from Customer c join Order o on c.Orderid=o.Orderid and c.Orderid = (select max(Orderid) from Customer where Customerid=c.Customerid)