﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / T-SQL (SS2K8)  / How to optimize this query / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Thu, 23 May 2013 21:08:56 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: How to optimize this query</title><link>http://www.sqlservercentral.com/Forums/Topic828698-392-1.aspx</link><description>Cross post, please keep to one thread[url]http://www.sqlservercentral.com/Forums/Topic828700-360-1.aspx[/url]</description><pubDate>Fri, 04 Dec 2009 02:40:10 GMT</pubDate><dc:creator>Dave Ballantyne</dc:creator></item><item><title>How to optimize this query</title><link>http://www.sqlservercentral.com/Forums/Topic828698-392-1.aspx</link><description>I have a query for a report which is basically aggregating some data from different tables as following:/*******************************************************/WITH CAT AS (SELECT DISTINCT    c.cat_id,    c.name FROM  c INNER JOIN pv ON c.cat_id=pv.cat_idWHERE      pv.step=1 and     c.status=0)SELECT c.name,	(select count(1) 	 from p inner join p2p on p.prod_id=p2p.prod_id					inner join pv on p2p.path_id = pv.path_id						 where    	   pv.cat_id=c.cat_id and	    p.status=0 and 	    p2p.status=0 	    ) AS 'Total products',	 (select count(1) 	  from p inner join  o on p.product_id=o.product_id					inner join p2p on p.prod_id=p2p.prod_id					inner join pv on p2p.path_id = pv.path_id	  where 			pv.cat_id=c.cat_id and			p.status=0 and 			o.status=0 and 			p2p.status=0 			 ) AS 'Total Reviews',		  	  (select count(1) 	   from p inner join p2p on p.prod_id=p2p.prod_id					  inner join pv on p2p.path_id = pv.path_id			   where 			pv.cat_id=c.cat_id and			p.status=0 and 			p2p.status=0 and 			(select count(1) from O where prod_id = p.prod_id and status=0)&amp;gt;1) AS 'Prod. With 1 Review'			From     CAT  c order by c.name/*************************************/as you can see in the above query I am using some common tables again and again for different aggragation purpose like p, p2p,pv are common tables used in all subqueries. As the no of record in each of these tables is very high so the query is running very slow.Can anyone please suggest me how can i optimize this query?Thanks </description><pubDate>Fri, 04 Dec 2009 02:32:55 GMT</pubDate><dc:creator>mabud_ncc</dc:creator></item></channel></rss>