如何减少查询执行时间

时间:2015-10-29 04:51:03

标签: sql sql-server sql-server-2008

this is the execution plan The image shows the results for the query and its taking 25secs for ~7500 rows

 SELECT dt AS Date
,monthname
,dayname
,(
    SELECT COUNT(1)
    FROM Calendar
    WHERE DATEPART(MM, dt) = DATEPART(MM, c.dt)
        AND DATEPART(YEAR, dt) = DATEPART(YEAR, c.dt)
    ) AS daysInMonth
FROM Calendar AS c
WHERE dt BETWEEN '2000-01-01 00:00:00'
    AND '2020-02-01 00:00:00'

上述查询用于获取特定日期的特定月份的天数。在这里我给出了日期范围和所有日期之间的所有日期,只显示那个月的日子。

图像显示查询的结果,并且对于~7500行采用25秒。有人可以帮我缩短时间。

1 个答案:

答案 0 :(得分:6)

试试这个。在这里,您只计算一次总数而不是7500次。 同时为dt字段

创建索引
with monthCount as (
      SELECT DATEPART(YEAR, dt) as m_year,
             DATEPART(MM, dt) as m_month
             COUNT(1) as total
      FROM Calendar
      GROUP BY 
            DATEPART(YEAR, dt),
            DATEPART(MM, dt)
)
SELECT dt AS Date
       ,monthname
       ,dayname
       ,total
FROM Calendar C
JOIN monthCount M
    on DATEPART(YEAR, C.dt) = M.m_year
   and DATEPART(MM, C.dt) = M.m_month
WHERE C.dt BETWEEN '2000-01-01 00:00:00'
               AND '2020-02-01 00:00:00'