выбрать всех клиентов, у которых были записи за каждый месяц - PullRequest
0 голосов
/ 12 февраля 2019

Как выбрать всех клиентов, у которых есть записи за каждый месяц?Здесь клиент будет выбран, потому что у него / нее были записи за каждый месяц.

+----------+--------+-------+
| customer |  date  | spend |
+----------+--------+-------+
| a        | 201801 |   5.5 |
| b        | 201801 |    16 |
| c        | 201801 |     7 |
| a        | 201802 |   3.2 |
| b        | 201802 |   4.6 |
| a        | 201803 |     3 |
| c        | 201803 |   1.2 |
+----------+--------+-------+

желаемый результат:

+----------+--------+-------+
| customer |  date  | spend |
+----------+--------+-------+
| a        | 201801 |   5.5 |
| a        | 201802 |   3.2 |
| a        | 201803 |     3 |
+----------+--------+-------+

Ответы [ 3 ]

0 голосов
/ 12 февраля 2019

Предполагая, что все строки имеют даты на 2018 год, с помощью этого:

select customer from customers
group by customer
having count(distinct date) = 12

вы можете получить всех клиентов, у которых есть строки для каждого месяца 2018 года.Поэтому вам нужно присоединить его к основной таблице:

select c.* from (
  select customer from customers
  group by customer
  having count(distinct date) = 12
) t inner join customers c
on c.customer = t.customer
order by c.customer, c.date

Если есть даты и для других лет:

select c.* from (
  select customer from customers
  where substr(date, 1, 4) = '2018'
  group by customer
  having count(distinct date) = 12
) t inner join customers c
where substr(c.date, 1, 4) = '2018'
on c.customer = t.customer
order by c.customer, c.date
0 голосов
/ 12 февраля 2019

При условии, что на клиента приходится только одна запись в месяц:

select t.*
from (select t.*, count(*) over (partition by customer) as cnt
      from t
     ) t cross join
     (select count(distinct date) as cnt
      from t
     ) tt
where t.cnt = tt.cnt;
0 голосов
/ 12 февраля 2019

Я сделаю так:

select * 
from customers
group by customer, date, spend 
having count(distinct month(date)) = 
                   (select count(distinct month(date))
                    from customers
                       ) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...