小编Met*_*urf的帖子

带有日期比较的子查询性能不佳

当使用子查询查找具有匹配字段的所有先前记录的总数时,在只有 50k 条记录的表上性能很差。如果没有子查询,查询会在几毫秒内执行。对于子查询,执行时间超过一分钟。

对于此查询,结果必须:

  • 仅包括给定日期范围内的那些记录。
  • 包括所有先前记录的计数,不包括当前记录,无论日期范围如何。

基本表模式

Activity
======================
Id int Identifier
Address varchar(25)
ActionDate datetime2
Process varchar(50)
-- 7 other columns
Run Code Online (Sandbox Code Playgroud)

示例数据

Id  Address     ActionDate (Time part excluded for simplicity)
===========================
99  000         2017-05-30
98  111         2017-05-30
97  000         2017-05-29
96  000         2017-05-28
95  111         2017-05-19
94  222         2017-05-30
Run Code Online (Sandbox Code Playgroud)

预期成绩

对于日期范围2017-05-29,以2017-05-30

Id  Address     ActionDate    PriorCount
=========================================
99  000         2017-05-30    2  (3 total, 2 prior to ActionDate)
98  111         2017-05-30    1  (2 total, 1 prior to ActionDate) …
Run Code Online (Sandbox Code Playgroud)

performance subquery azure-sql-database query-performance

15
推荐指数
1
解决办法
421
查看次数