加入两个聚合查询

时间:2018-03-11 10:12:05

标签: sql

我有两个看起来像这样的表

用户

id | created_at

付款

id | created_at

我需要一个按年和月分组的表,其中包含用户数和付款数

统计

month | year | users | payments

其中users列包含注册用户数和payments - 付款数量。我可以分别得到两张桌子,但我怎么加入呢?

select 
    month(created_at) as month, 
    year(created_at) as year, 
    count(*) users
from 
    users 
group by 
    month, year 
having 
    users > 0 
order by 
    year desc, month desc;

select 
    month(created_at) as month, 
    year(created_at) as year, 
    count(*) payments
from 
    payments 
group by 
    month, year 
having 
    payments > 0 
order by 
    year desc, month desc;

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西:

select a.*, b.payments from (
    select month(created_at) as month, year(created_at) as year, count(*) users
    from users group by month, year having users > 0 order by year desc, month desc
) a left join (
    select month(created_at) as month, year(created_at) as year, count(*) payments
    from payments group by month, year having payments > 0 order by year desc, month desc
) b on a.month = b.month and b.year = b.year

答案 1 :(得分:0)

users > 0payments > 0的比较毫无用处。另外,子查询中的order by没有意义。

您可以使用full join

执行此操作
select month, year, coalesce(users, 0) as users, coalesce(payments, 0) as payments
from (select month(created_at) as month, year(created_at) as year, 
             count(*) as users
      from users
      group by month, year 
     ) u full join
     (select month(created_at) as month, year(created_at) as year,
             count(*) as payments
      from payments
      group by month, year
     ) p
     using (month, year)
order by year desc, month desc;

如果您知道自己拥有所有月份的用户和付款(您关心的话),则可以使用inner join而不是full join