How to optimize this query

  • 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

  • Cross post, please keep to one thread

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



    Clear Sky SQL
    My Blog[/url]

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply