繁体   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