简体   繁体   English

连接两个汇总查询

[英]Joining two aggregated queries

I have 2 tables that look like this 我有2张桌子,像这样

users : 用户

id | created_at

payments : 付款方式

id | created_at

I need a table that is grouped by year and month and contains both number of users and payments 我需要一个按年和月分组并包含用户数和付款数的表

stats : 统计资料

month | year | users | payments

Where users column contains number of registered users and payments - number of payments. users列包含注册用户数和payments - payments数。 I can get two tables separately, but how can I join them? 我可以分别获得两个表,但是如何加入它们呢?

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;

I think that's what you're looking for : 我认为这就是您要寻找的:

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

The comparison to users > 0 and payments > 0 are useless. users > 0payments > 0是无用的。 In addition, order by in subqueries is meaningless. 另外,在子查询中order by是没有意义的。

You can do this with a full join : 您可以通过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;

If you know you have users and payments for all months (that you care about), you can use an inner join rather than a full join . 如果您知道所有月份(您在意的)都有用户和付款,则可以使用inner join而不是full join

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM