简体   繁体   中英

Optimizing SQL SERVER 2005 query

Good morning,

I got this part of a SQL query:

WITH HC AS (
    SELECT Dia, Mes, Anyo, Hora, Energia AS HidroConv 
    FROM Calendar 
    LEFT OUTER JOIN OMP_PDBC_STOTA O 
        ON Calendar.Y = O.Anyo AND Calendar.M = O.Mes 
        AND Calendar.D = O.Dia AND Calendar.H = O.Hora 
    WHERE (Codigo = 1) AND Calendar.dt BETWEEN '12/31/2013' AND '01/01/2014')

SELECT Calendar.dt AS Fecha, Calendar.Y, Calendar.M, Calendar.D, Calendar.H, 
       HC.HidroConv
FROM Calendar 
LEFT OUTER JOIN HC 
     ON Calendar.Y = HC.Anyo AND Calendar.M = HC.Mes 
     AND Calendar.D = HC.Dia AND Calendar.H = HC.Hora 
WHERE dt BETWEEN '12/31/2013' AND '01/01/2014' 
ORDER by dt, h

On the WITH part, I have got another 12 queries. Then, on the SELECT part, I retrieve one column per SELECT on the WITH part. On the FROM part, there is a LEFT OUTER JOIN for each one of them, always having Calendar on the left side of the join.

The execution of this big query is taking more than 2 minutes, and I desperately need to reduce that time to, maybe 15 seconds or less. Some of the tables, like OMP_PDBC_STOTA have 3 million rows.

Do you have any idea about how to optimize this query??

Thank you so much for your help.

Ricardo

Does this query give the same output ?

SELECT Calendar.dt AS Fecha, Calendar.Y, Calendar.M, Calendar.D, Calendar.H, Energia AS HidroConv
FROM Calendar 
    LEFT OUTER JOIN OMP_PDBC_STOTA O 
        ON Calendar.Y = O.Anyo AND Calendar.M = O.Mes 
        AND Calendar.D = O.Dia AND Calendar.H = O.Hora 
WHERE  
    Calendar.dt BETWEEN '12/31/2013' AND '01/01/2014' 
    AND Codigo = 1
ORDER by dt, h

If so, it will be faster, tell me if i'm wrong i'll help you.

I found out I don't really need Calendar to get to the same results.

What do you think about this way of doing it?

SELECT  anyo, mes, dia, hora, Energia AS HidroConv
FROM OMP_PDBC_STOTA
WHERE  
    CAST(CAST(mes AS VARCHAR) + '/' + CAST(dia AS VARCHAR) + '/' + CAST(anyo AS VARCHAR) as datetime) BETWEEN '12/31/2013' AND '01/01/2014' 
    AND Codigo = 1
ORDER by mes,dia, hora

Can't find a proper way of converting the smallints (mes,dia,anyo) to a datetime though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM