简体   繁体   中英

SQL: improving join efficiency

If I turn this sub-query which selects sales persons and their highest price paid for any item they sell:

select *,
    (select top 1 highestProductPrice
     from   orders o
     where  o.salespersonid = s.id
     order by highestProductPrice desc ) as highestProductPrice
from salespersons s

in to this join in order to improve efficiency:

select *, highestProductPrice
from   salespersons s join (
       select salespersonid, highestProductPrice, row_number(
           partition by salespersonid 
           order by salespersonid, highestProductPrice) as rank
       from orders ) o on s.id = o.salespersonid

It still touches every order record (it enumerates the entire table before filtering by salespersonid it seems.) However you cannot do this:

select *, highestProductPrice
from   salespersons s join (
       select salespersonid, highestProductPrice, row_number(
           partition by salespersonid 
           order by salespersonid, highestProductPrice) as rank
       from orders 
       where orders.salepersonid = s.id) o on s.id = o.salespersonid

The where clause in the join causes a `multi-part identifier "s.id" could not be bound.

Is there any way to join the top 1 out of each order group with a join but without touching each record in orders?

Try

SELECT
  S.*, 
  T.HighestProductPrice
FROM   
  SalesPersons S

  CROSS APPLY 
  (
    SELECT TOP 1 O.HighestProductPrice
    FROM Orders O
    WHERE O.SalesPersonid = S.Id
    ORDER BY O.SalesPersonid, O.HighestProductPrice DESC
  ) T 

would

select s.*, max(highestProductPrice)
   from salespersons s 
   join orders o on o.salespersonid = s.id
group by s.*

or

select s.*, highestProductPrice
   from salespersons s join (select salepersonid, 
                             max(highestProductPrice) as highestProductPrice
                             from orders o) as o on o.salespersonid = s.id

work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM