合并两个按月计算的查询

时间:2010-07-20 05:04:00

标签: sql

this question on Meta的启发,我在Stack Exchange Data Explorer上写了两个查询,一个计算SO上Questions Asked by Month的总数,另一个计算Bounties Awarded by Month。如何组合它们以便在一个查询中输出?我想看 年份,月份,问题,赏金和金额在一份报告中。

问题记录在Posts表中PostTypeId = 1,但赏金记录在投票表中,其中VoteTypeId = 9。

1 个答案:

答案 0 :(得分:4)

我在记事本中写到这个&没有在SO上使用数据资源管理器。

select Isnull(V.Year, P.Year) As Year,
Isnull(V.Month, P.Month) As Month,
Isnull(V.Bounties, 0) As Bounties,
Isnull(V.Amount,0) As Amount ,
P.Questions
FROM
(
select
datepart(year, Posts.CreationDate) Year,
datepart(month, Posts.CreationDate) Month,
count(Posts.Id) Questions
from Posts
where PostTypeid = 1 -- 1 = Question
group by datepart(year, Posts.CreationDate), datepart(month, Posts.CreationDate)
) AS P
left JOIN
(
select
datepart(year, Votes.CreationDate) Year,
datepart(month, Votes.CreationDate) Month,
count(Votes.Id) Bounties,
sum(Votes.BountyAmount) Amount
from Votes
where VoteTypeId = 9 -- 9 = BountyAwarded
group by datepart(year, Votes.CreationDate), datepart(month, Votes.CreationDate)
) AS V
ON P.Year = V.Year AND P.Month = V.Month
order by P.Year, P.Month