0

Does anyone have any suggestions on making the following select statement more efficient? It is a very simple query but the SSRS using the code hits the timeout set.

SELECT   
   G.A
   ,B = IsNull(Avg(CAST(T.B as decimal)), 0)
   ,C = Sum(T.C)
   ,D = IsNull(Avg(CAST(T.D as decimal)), 0)
FROM 
   TableA as G 
INNER JOIN 
   TableB as T ON T.An_ID = G.An_ID
group by G.A

This is a snippet of the code with identical grouping in the bigger script of the SP that the SSRS is using.

9
  • Do you have indexes on An_ID in both TableA and TableB? Also should there be a GROUP BY clause in there somewhere? Commented Mar 24, 2015 at 21:26
  • Yes both have IDs have indexes. Commented Mar 24, 2015 at 21:27
  • 1
    Did you try running it in SQL Server Management Studio with the show query plan option? Did it recommend any indexes? Commented Mar 24, 2015 at 21:31
  • 2
    Show the execution plan. Commented Mar 24, 2015 at 21:43
  • 1
    This query is syntactically incorrect, because it is an aggregation query with no group by, and g.a is not in an aggregation function. Commented Mar 24, 2015 at 22:07

1 Answer 1

1

For this query:

SELECT G.A, B = IsNull(Avg(CAST(T.B as decimal)), 0),
       C = Sum(T.C), D = IsNull(Avg(CAST(T.D as decimal)), 0)
FROM TableA G INNER JOIN 
     TableB T
     ON T.An_ID = G.An_ID
GROUP BY G.A;

You want indexes on TableB(An_ID) and TableA(An_Id, A).

My guess is that the joins are producing a very large number of intermediate rows. You can get the count by doing:

select sum(a.cnt * b.cnt)
from (select an_id, count(*) as cnt from tablea group by an_id) a join
     (select an_id, count(*) as cnt from tableb group by an_id) b
     on a.an_id = b.an_id;

You can find the offensive combinations:

select top 100 a.cnt * b.cnt, a.an_id
from (select an_id, count(*) as cnt from tablea group by an_id) a join
     (select an_id, count(*) as cnt from tableb group by an_id) b
     on a.an_id = b.an_id
order by a.cnt * b.cnt desc
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.