2011-07-19 106 views
1

如果我把這個子查詢,其選擇支付任何項目銷售人員和他們的最高價,他們賣:SQL:提高加盟效率

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

,以提高工作效率加盟

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 

它仍然觸及每一個訂單記錄(它通過salespersonid似乎濾波前枚舉整個表。)但是你不能做到這一點:

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 

連接中的where子句導致「多部分標識符」s.id「無法綁定。

有什麼方法可以通過連接將每個訂單組中的前1個連接起來,但沒有觸及訂單中的每條記錄?

+0

你是什麼意思'觸及每個記錄'?它將不得不觸及每一條記錄**以找出哪一個需要成爲頂級1 **。如果你沒有按照你想要的順序存在*索引,那麼每次都必須在運行時執行(當然,它可能會緩存答案,或者構建一個可重用的臨時索引)。 –

+0

當您將枚舉篩選爲僅可連接記錄時,查詢所花費的時間顯着減少。換句話說,只對我想要排名的記錄進行排名,而不排序基於salespersonid不會加入的記錄 –

回答

2

嘗試

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 
+0

這非常有趣,它將允許內部條件引用外部表。我會嘗試一下。 –

+0

真的比使用排序的子選擇更有效嗎? –

1

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

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

工作?

+0

我簡化了選擇。原始文件包含一對字段以查找集合中最低的字段。但是,我可以在Max()函數中彙總它們。我只是想知道,在S. *上選擇截然不同會導致更大的延遲。 +1在正確的軌道上。 –