我在同一张桌子上有2个查询,我预计会有类似的表现,但我仍然会有很大的差异 - 30秒对比~1秒。
查询1:为当月计算用户数
b()
查询2:计算本周的用户数
SELECT datepart(year,getdate()) as TheYear,
DATEPART(month, GETDATE()) AS TheMonth,
COUNT(DISTINCT Username) AS TheUsers
FROM dbo.[AP-Data]
WHERE datepart(year,RequestDate) = datepart(year,getdate())
AND datepart(month,RequestDate) = datepart(month,getdate())
该表有大约350万条记录,并由SELECT datepart(year,getdate()) as TheYear,
DATEPART(week, GETDATE()) AS TheWeek,
COUNT(DISTINCT Username) AS TheUsers
FROM dbo.[AP-Data]
WHERE datepart(year,RequestDate) = datepart(year,getdate())
AND datepart(week,RequestDate) = datepart(week,getdate())
编制索引。本月的计数正在进行全表扫描,因此需要30秒,本周的一次是在~1秒内进行RID查询 - 此信息来自执行计划。
知道为什么会有差异吗?
答案 0 :(得分:3)
尝试这些查询怎么样?
SELECT year(getdate()) as TheYear, month(GETDATE()) AS TheMonth,
COUNT(DISTINCT Username) AS TheUsers
FROM dbo.[AP-Data]
WHERE RequestDate >= dateadd(month, datediff(month, 0, getdate()), 0);
和
SELECT year(getdate()) as TheYear, month(GETDATE()) AS TheMonth,
COUNT(DISTINCT Username) AS TheUsers
FROM dbo.[AP-Data]
WHERE RequestDate >= dateadd(week, datediff(week, 0, getdate()), 0);
在列上使用函数通常会阻止编译器使用索引。以上假设您没有将来的请求日期。