Добавьте COUNT (*) из разных таблиц, включая операторы WHERE и GROUP BY - PullRequest
0 голосов
/ 03 июля 2018

У меня три запроса вроде этого:

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 голосов
/ 03 июля 2018

Полагаю, вы могли бы использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...