這個查詢大約需要01:30
運行:如何優化這個TSQL
select DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
, count(t2.UserId)
, count(*) - count(t2.UserId)
from Events t1
left join (select c.UserId, min(c.OccurredOn) FirstOccurred
from Events c
where [OccurredOn] between @start and @end
group by c.UserId) t2 on t1.OccurredOn = t2.FirstOccurred and t1.UserId = t2.UserId
where t1.EventType = @eventType
and t1.[OccurredOn] between @start and @end
group by DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
order by DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
如果我從子查詢中刪除WHERE
條款,它運行瞬間。
自身運行子查詢,用WHERE
需要< 1S
如果我SELECT
子查詢到表變量第一,並加入到,整個查詢中19S運行。
的Events
表的樣子:
[Events](
[EventType] [uniqueidentifier] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
[OccurredOn] [datetime] NOT NULL,
)
我有以下primary, nonclustered, nounique
指標:
- 事件類型
- 用戶ID
- OccurredOn
這裏S中的執行計劃
使用SQL Server 2008
兩件事情:
- 回事請告訴我?發生什麼事會讓這個緩慢?
- 如何加快速度?
感謝
請**顯示我們**表結構,列和它們的數據類型,告訴我們你有什麼索引... - 還有什麼** VERSION **的SQL Server使用? – 2012-07-21 08:25:25
好點,意味着添加。待機 – 2012-07-21 08:25:54
你看過執行計劃嗎?它顯示了什麼? – 2012-07-21 08:26:40