【发布时间】:2012-06-26 15:43:54
【问题描述】:
我有一个表“customertransactions”,其中有一列“transactiondate”类型为 DateTime。
我将通过以下方式查询它:
SELECT SUM(balance) AS totalbal FROM customertransactions WHERE accountcode=?
AND (MONTH(GETDATE())-MONTH(transactiondate)+12*(YEAR(GETDATE())-YEAR(transactiondate)))>= 3
...显然为“accountcode”传递了一个经过清理的参数。
我的问题是 - 我如何最好地创建一个索引来优化它?
谢谢。
【问题讨论】:
-
您的意思是“交易超过 3 个月”吗?那么你的代码是错误的,应该是
where datediff(m, transactiondate, getdate()) >= 3。 -
您确定在尝试调整索引之前不能更好地编写查询吗?什么是业务规则?
-
@GSerg 实际上,您的 WHERE 子句不是 sargable。应该写成:
where transactiondate <= dateadd(month, -3, getdate())。这将允许考虑transactiondate上的索引。 -
好的,采纳 GSerg 的建议,那么它只是一个关于“交易日期”的直截了当的非聚集索引?
-
@AlanB 是的,但也接受 RedFilter 的建议。
标签: sql-server sql-server-2008 tsql indexing