gpt4 book ai didi

sql - 如何减少查询执行时间

转载 作者:行者123 更新时间:2023-12-04 14:09:58 25 4
gpt4 key购买 nike

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'

上面的查询是为了获取特定日期的特定月份的天数。这里我给出日期范围,对于范围之间的所有日期,我只显示那个月的天数。

图像显示了查询的结果,它用了 25 秒的时间查询了大约 7500 行。谁能帮我缩短时间。

最佳答案

试试这个。在这里你只计算总数一次而不是 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'

关于sql - 如何减少查询执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com