Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

How to optimize this query Expand / Collapse
Author
Message
Posted Friday, December 4, 2009 2:32 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, June 17, 2013 8:36 AM
Points: 5, Visits: 51
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_id
WHERE
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)>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
Post #828698
Posted Friday, December 4, 2009 2:40 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, July 15, 2014 7:03 AM
Points: 1,949, Visits: 8,303
Cross post, please keep to one thread

http://www.sqlservercentral.com/Forums/Topic828700-360-1.aspx




Clear Sky SQL
My Blog
Kent user group
Post #828703
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse