如何使SELECT更快

时间:2016-08-25 20:26:18

标签: sql-server

我有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的编号为:dcodigodfechatipo1,并且有超过600,000行。

提前致谢

2 个答案:

答案 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函数并改为测试日期常量。