【问题标题】:Better option to mention date range in CTE query?在 CTE 查询中提及日期范围的更好选择?
【发布时间】:2015-02-02 06:37:39
【问题描述】:

我只是想知道如何让我的 CTE 查询执行得更快。

选项1:

;with cte as
(
select Name , count(*) as TotalCount  from dbo.table 
where date_value > getdate()-120
)
select * from cte 
where count(*) > 100 

选项2:

declare @date_value date;
set @date_value = getdate()-120;

;with cte as
(
select Name , count(*) as TotalCount  from dbo.table 
where date_value > @date_value
)
select * from cte 
where count(*) > 100 

选项 2 的运行速度比 1 快一点,只是上述查询中的变化是使用局部变量和没有位置变量。

我的问题是,如果我们使用局部变量作为日期范围,会提高查询性能吗?

仅供参考: 数据库服务器:sql server 2008/R2, 表行数:100 万, 运行时间:21 分钟

有什么想法吗?

【问题讨论】:

  • 很确定查询没有运行。你能发布实际的查询吗?
  • 在尝试进行性能调整(任何事情)之前,您是否根据实际目标实际测量了性能,并且性能是否比要求的差?如果没有,只需编写清晰的代码并继续前进。如果您确实需要调整性能,您是否测量过哪里性能较差?这是问题的实际位置吗?如果是这样,切换到局部变量形式是否真的可以解决您的性能问题?如果是这样,请继续。如果没有,请查看其他地方。
  • 我怀疑你可以在没有分组的情况下计算()。 group by 和 "have count() > 300" 有什么问题?无需 CTE。

标签: sql sql-server sql-server-2008-r2 common-table-expression database-performance


【解决方案1】:

性能不是因为CTE。还有你为什么要使用CTE? CTE 里面是否有更多脚本。如果是,那么您应该提供全面检查。 i) 最后不是使用两次 Count(*),而是使用一次 row_number。

ii) 您是否在日期列上创建了索引?您应该。 iii) 存在 where 条件不会使用索引。

试试这个,请给反馈。运行几次。

select * from 
(
select Name ,
row_number()over(order by date_value) rn  from dbo.table 
where date_value > dateadd(d,-120,getdate())
)tbl where rn>100

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多