Basically you have derived queries that are referencing derived queries joining to other derived queries which have subqueries,This might work better, untested. Remember the CTE gets re-propagated in each reference. so even though it runs fine standalone, the number of reads increases wildly based on the subsequent select....almost recursively.;with qtysold as (select itemid = s.itemid, qtysold = SUM(sliretainquantity), from safe_line_item s on s.itemid = s.itemidinner join transactions t on i.txid = t.txid Where t.txstartdate >= '20110209' and t.txstartdate <= '20110216'),priorday as (itemid = s.itemid, previous = SUM(sliretainquantity), from safe_line_item s on s.item = s.itemid inner join transactions t on i.txid = t.txid Where t.txstartdate >= '20110202' and t.txstartdate <= '2011028')SELECT i.id,i.title,(qtysold-previous)FROM imitem i inner join qtysold qs on i.id = qs.itemidleft join previousday pd on i.id = pd.itemidleft join inventory inv on i.id = inv.itemid
I would just do it all in one select and avoid the recursion in the CTE inside a CTE., but you can likely attack this several different ways.SELECT i.id,i.title,qtysold = SUM(Case WHen txstartdate >= '2/9/2011' and txstartDate < '2/16/2011' then sliretailquantity else 0 end),priorday = SUM(Case WHen txstartdate >= '2/2/2011' and txstartDate < '2/8/2011' then sliretailquantity else 0 end),netchange = SUM(Case WHen txstartdate >= '2/9/2011' and txstartDate < '2/16/2011' then sliretailquantity else 0 end) - SUM(Case WHen txstartdate >= '2/2/2011' and txstartDate < '2/8/2011' then sliretailquantity else 0 end)FROM imitem i inner join sale_line_item qs on i.id = qs.itemidleft join sale_line_item pd on i.id = pd.itemidleft join inventory inv on i.id = inv.itemid
Poor planning on your part does not constitute an emergency on my part.