簡體   English   中英

具有 cte 和 rownumber 性能

[英]With cte and rownumber performance

我有一個包含超過 350 000 000 的表 vente(sales)。我嘗試執行以下查詢,但花了很長時間:

 select t1.[datecol],t1.[Prix de vente TTC],t1.Quantité 
      from [Vente] t1
      inner join (select distinct [datecol],[Code Article],[Code Structure],[Code Site],
      row_number() over(Partition by  [Code Article],[Code Structure],[Code Site] order by [datecol]desc ) as rn

      from (select distinct  [datecol],[Code Article],[Code Structure],[Code Site]
           from [Vente] t2
            where promo = 0
                  and ([Code Article] is not null) 
                  and ([Code Structure] is not null) 
                  and ([Prix de Revient] is not null)
    )g
          ) a
           on a.datecol=t1.datecol
            and t1.[Code Article] = a.[Code Article]
            and t1.[Code Structure]=a.[Code Structure]
            and t1.[Code Site]=a.[Code Site]
            where  promo = 0
            and (t1.[Code Article] is not null) and (t1.[Code Structure] is not null) and ([Prix de Revient] is not null ) 
            and
              rn <= 28

執行計划

在此處輸入圖片說明

嗯,這就是row_number的價格。 它不是搜索 - 它正在排序和構建一個新列。 這就像你在說“你什么都不知道,sql server!讓我告訴你你有什么日期以及如何計算desc順序。這個日期排在第一,這是第二,......”

我看到以前的帖子有計划,提到了一些索引,所以讓我們試試這個(請發布它的計划圖片):

select t1.[datecol],t1.[Prix de vente TTC],t1.Quantité 
from [Vente] t1
outer apply
(
  select top 28 distinct t2.[datecol]
  from [Vente] t2
  where t2.[Code Article] = t1.[Code Article]
    and t2.[Code Structure]=t1.[Code Structure]
    and t2.[Code Site]=t1.[Code Site]
  order by t2.[datecol] desc
) t2
where t1.promo = 0
  and (t1.[Code Article] is not null)
  and (t1.[Code Structure] is not null) 
  and (t1.[Prix de Revient] is not null ) 
  and t1.datecol = t2.datecol

我不確定您的最終目標和實際要求是什么(關於那些“28 天”)。 另一種方法是先找出天數,將它們存儲在臨時表中,然后加入。

正如我已經提到的,我不知道要求,所以不能說是否可以通過應用一個簡單的過濾器來完成所有任務where t1.datecol >= dateadd(dd, -28, cast(getdate() as date)) - 但我建議考慮一下。

但不知何故,我確信您不需要一年前的數據。 應用此過濾器,切斷您肯定不需要的數據。 計算set @startdate = dateadd(yy, -1, getdate()) (可能小於一年)並將此過濾器應用於內部和外部查詢。 這將切斷您不需要處理的大量數據。

現在,除了promo=0和計算日期過濾器之外,您沒有任何過濾器,因此您幾乎可以處理所有這 350M 條記錄。 應用一些過濾器。 即使沒有人提及,也要想想他們。 你肯定不需要太舊的數據,你可能不需要price=0quantity=0 ,可能是別的東西。 隔斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM