我有SELECT
使用SQL Server 2012:
SELECT
dcodigo AS cuenta,
SUM(dvalordeb) AS sumadebitop,
SUM(dvalorcre) AS sumacreditop
FROM
diario
WHERE
diario.anulado = 0
AND LEN(diario.dcodigo ) > 0
AND MONTH(diario.dfecha) <= 11
AND YEAR(diario.dfecha) = 2015
AND diario.tipo1 <> 'CI'
GROUP BY
dcodigo
但需要大约2,8分钟。我能做些什么来加快执行速度?
表格diario
的编号为:dcodigo
,dfecha
和tipo1
,并且有超过600,000行。
提前致谢
答案 0 :(得分:1)
试试这个:
如果dfecha
仅为日期,则
SELECT dcodigo as cuenta,
sum(dvalordeb) sumadebitop,
sum(dvalorcre) sumacreditop
FROM diario
WHERE anulado = 0
AND dcodigo is not null
and dcodigo <> ''
AND dfecha between '20150101' and '20151031'
AND tipo1 <> 'CI'
GROUP BY dcodigo
如果dfecha
有日期和时间,那么
SELECT dcodigo as cuenta,
sum(dvalordeb) sumadebitop,
sum(dvalorcre) sumacreditop
FROM diario
WHERE anulado = 0
AND dcodigo is not null
and dcodigo <> ''
AND dfecha >='20150101'
and dfecha < '20151101'
AND tipo1 <> 'CI'
GROUP BY dcodigo
答案 1 :(得分:1)
基于函数调用的条件不会从索引中受益。
将LEN(diario.dcodigo)>0
替换为diario.dcodigo<>''
。但基本问题是这个列是否确实包含空字符串。我想空字段只包含NULL
。在这种情况下,您应该测试diario.dcodigo IS NOT NULL
。如果它可以像NOT (diario.dcodigo IS NULL OR diario.dcodigo = '')
一样进行测试,也不要忘记括号。
正如Lamak评论的那样,忽略MONTH和YEAR函数并改为测试日期常量。