【问题标题】:Alternate SQL Server query by performance?按性能替代 SQL Server 查询?
【发布时间】:2022-01-22 14:39:45
【问题描述】:

我正在使用的查询:

select SUM(marks) 
from Table1 
where name = ? 
  and Date = (select top 1 Date 
              from Table1 
              where name =? 
                and Date < ? 
              order by Date desc) 

表1:

id name marks Date
1 abc 34 01/01/2021
2 abc 15 05/01/2021
3 abc 20 05/01/2021
4 def 34 05/01/2021
5 abc 12 10/01/2021
select sum(marks) 
from Table1 
where name ='abc' 
  and Date = (select top 1 Date 
              from Table1 
              where name = 'abc' 
                 and Date < 10/01/2021 
              order by Date desc) 

结果35

【问题讨论】:

  • 你的问题到底是什么?
  • 感谢您的提问,我要求提供更短的时间来获取所需结果的备用查询?
  • 是什么让你觉得当前查询很慢?对于与性能相关的问题,我们需要一份执行计划的副本,使用“粘贴计划”
  • @KuldeepSingh,查看答案并将其标记为useful。如果没有帮助,请添加comment。即使某些解决方案有帮助,也不要让问题悬而未决。

标签: sql sql-server tsql


【解决方案1】:

使用RANK() 会花费相对较少的时间:

select sum(marks)
from
   (
   select *, rank()OVER(order by date desc) as rnk
   from table1
   where name ='abc' and Date < '10/01/2021'
   ) as we
where rnk=1

结果:35

说明:

您的查询在 WHERE 子句中使用子查询,它将检查每个条件,并且您正在过滤名称 abc 2 次。或者,我只做一次并在FROM 子句中提供子查询,这大大节省了时间。

看demo here随着时间的流逝(已经做了一些额外的虚拟数据来检查时间)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多