I am trying to summarize banner ad views from a table that is pretty good size(18,243,847 rows). I need a count for views in the past two years. I tried adding an index to the date and tried different variations of the query below. Most runs are about 25 seconds, however it seems when passed in a web service, the target page is timing out. I know the issue is with count, but have not been able to reduce that portion to lower than 11 seconds. Seems like not a lot, but why the issue with my web service? Anyway, first things first, is this query doing the best I can do?
SELECT ba.adID, ba.name, ba.description, ba.startDate, ba.endDate, isNull(v.viewCount,0) AS viewCount, isNull(c.clickCount,0) AS clickCount
FROM bannerAds ba
LEFT OUTER JOIN (SELECT adID, count(viewID) AS viewCount
FROM bannerAdsViews
WHERE viewDateTime IS NOT NULL AND viewDateTime >= DateAdd(yy, -2, GetDate())
GROUP BY adID) v ON ba.adID = v.adID
LEFT OUTER JOIN (SELECT adID, count(viewID) AS clickCount
FROM bannerAdsViews
WHERE clickDateTime IS NOT NULL AND viewDateTime >= DateAdd(yy, -2, GetDate())
GROUP BY adID) c ON ba.adID = c.adID
WHERE viewCount > 0
ORDER BY name ASC
FOR XML RAW ('Banner'), ROOT ('Banners');