将计数和求和查询连接到单个数据集中

时间:2013-09-18 16:15:11

标签: sql-server-2008-r2 ssrs-2008

是否有可能以某种方式将以下两个查询加入到可在SSRS报告的Tablix中使用的单个数据集中?

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

最终报告看起来像这样:

       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

我尝试过使用派生表,但结果不正确,因为Pend标志会过滤掉一些计数结果。我已经阅读了一些关于Common Table Expressions的内容,但是我不完全理解它们何时会用于如何使用它们。对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

你为什么不加入他们?

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