sql-server-2008-r2ssrs-2008

Join Count and Sum Queries into Single Dataset


Is it possible to somehow join the following two queries into a single dataset that can be used in tablix in an SSRS report?

Table Policy
------------
PolNum
SubmitDate
ProdID
Pend    

Table Product
-------------
ProdID
ProdCat

Table Prem
---------
PolNum
Prem

Query 1

Select Count(PolNum), DATEPART(wk, SubmitDate)
From Policy INNER JOIN Product on Policy.ProdID = Product.ProdID
Where (year(SubmitDate) = year(getdate()))
Group by ProdCat, SubmitDate

Query2

Select sum(Prem), DATEPART(wk, SubmitDate)
From Policy INNER JOIN Product on Policy.ProdID = Product.ProdID INNER JOIN 
Prem on Pol Pol.PolNum = Prem.PolNum
Where (Pend = 1)
Group By ProdCat, SubmitDate

The final report would look something like this:

       Cat1    Cat2      Cat3     PremCat1  PremCat2    Premcat3
Week 1     5     4       5        65        25        95
Week 2     2     5       6        45        10        65
Week 3     3     6       15       13        15        96    
Week 4     5     7       13       98        45        35

I've tried using a derived table, but the results aren't correct because The Pend flag will filter out some of the results for the count. I've read some about Common Table Expressions, but I do not fully understand when they would be used of how to use them.


Solution

  • Why don't you just join them?

    select * from 
    (Select Count(PolNum) as PolCount, DATEPART(wk, SubmitDate) t1week
    From Policy INNER JOIN Product on Policy.ProdID = Product.ProdID
    Where (year(SubmitDate) = year(getdate()))
    Group by ProdCat, SubmitDate) as t1
    inner join 
    (Select sum(Prem) as sumPrem, DATEPART(wk, SubmitDate) t2week
    From Policy INNER JOIN Product on Policy.ProdID = Product.ProdID INNER JOIN 
    Prem on Pol Pol.PolNum = Prem.PolNum
    Where (Pend = 1)
    Group By ProdCat, SubmitDate) as t2
    on t1.t1week = t2.t2week