从包括WHERE语句和GROUP BY在内的不同表中添加COUNT(*)

时间:2018-07-03 13:50:08

标签: postgresql

我有三个这样的查询:

select count(*) as customers, created_at::date as date from table1 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC

select count(*) as customers, created_at::date as date from table2 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC

select count(*) as customers, created_at::date as date from table3 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC

我需要的是最后两列:三个表中的日期和总计customers。我尝试了一个子查询,但是不确定如何正确放置GROUP BY而不出错。我尝试过这样的事情:

select ((select count(*) as customers, created_at::date as date from table1 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC)+(select count(*) as customers, created_at::date as date from table2 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC)+(select count(*) as customers, created_at::date as date from table3 where subscription_ends_at IS NOT NULL group by created_at::date order by created_at::date ASC)) AS SumCount

1 个答案:

答案 0 :(得分:3)

我想您可以使用union all合并表中的数据,然后执行汇总

select t.date, count(*)
from (
    select  created_at::date as date from table1 where subscription_ends_at IS NOT NULL 
    union all
    select  created_at::date as date from table2 where subscription_ends_at IS NOT NULL
    union all
    select created_at::date as date from table3 where subscription_ends_at IS NOT NULL
) t
group by t.date
order by t.date