代码之家  ›  专栏  ›  技术社区  ›  Bill the Lizard

合并两个按月计算的查询

sql
  •  3
  • Bill the Lizard  · 技术社区  · 14 年前

    灵感来自 this question on Meta ,我在Stack Exchange Data Explorer上编写了两个查询,其中一个用于计算 Questions Asked by Month 就这样,另一个也算数了 Bounties Awarded by Month . 如何组合它们,以便在一个查询中获得输出?我想看看 年、月、问题、奖金和金额在一份报告中。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Cœur Gustavo Armenta    7 年前

    我在记事本里写的;还没有使用过data explorer。

    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