I have a request that takes about 11 seconds to run on a single date. I want to run the same query in a few days. In other words, I want to be able to return snapshots in a few days. Here is my original request:
SELECT COUNT(*) AS 'Number of Cars', d.ManufacturerName AS 'Make', d.Name AS 'Model', c.name AS 'Car Class' FROM CarRating a INNER JOIN OwnedCar b ON a.OwnedCarID = b.OwnedCarID INNER JOIN CarClass c ON a.CarClassID = c.CarClassID INNER JOIN BaseCar d ON b.BaseCarID = d.BaseCarID WHERE @myDate < a.ExpiredWhen AND @myDate >= a.EffectiveWhen GROUP BY d.Name, c.name,d.ManufacturerName
As I said, the request takes 11 seconds. To execute this query for multiple dates, I use a date table and cross-apply it to the above query:
SELECT [DATE], b.* FROM DimDate CROSS APPLY (SELECT COUNT(*) AS 'Number of Cars', d.ManufacturerName AS 'Make', d.Name AS 'Model', c.name AS 'Car Class' FROM CarRating a INNER JOIN OwnedCar b ON a.OwnedCarID = b.OwnedCarID INNER JOIN CarClass c ON a.CarClassID = c.CarClassID INNER JOIN BaseCar d ON b.BaseCarID = d.BaseCarID WHERE dimDate.Date < a.ExpiredWhen AND dimDate.Date >= a.EffectiveWhen GROUP BY d.Name, c.name,d.ManufacturerName) b WHERE DimDate.Date between @StartDate and @EndDate
This request takes 49 seconds, even for one day. Why is it slow? Is there a better way to do this?
source share