将计数和求和查询加入单个数据集

Posted

技术标签:

【中文标题】将计数和求和查询加入单个数据集【英文标题】:Join Count and Sum Queries into Single Dataset 【发布时间】:2013-09-18 16:15:10 【问题描述】:

是否有可能以某种方式将以下两个查询加入到单个数据集中,以便在 s-s-rS 报告的 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

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

【问题讨论】:

【参考方案1】:

你为什么不加入他们?

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

【讨论】:

以上是关于将计数和求和查询加入单个数据集的主要内容,如果未能解决你的问题,请参考以下文章

将两个查询与计数函数组合为一个结果集

MongoDB - 多个查询和单个文档结果

数据冗余 - 加入大型结果集

SQL按间隔分组,计数和求和

Pandas DataFrame groupby,跨列计数和求和

Analysis Services 2005 OLAP 多维数据集:我可以在 nvarchar 列上创建不同的计数度量吗?