Вы можете получить в первый раз, когда кто-то заказал, используя оконную функцию (доступную в MySQL 8+), а затем использовать эту информацию для агрегирования:
select year(date), month(date),
count(distinct case when first_date = date then client end) as new,
count(distinct case when first_date < date then client end) as repeat,
count(distinct client) as total
from (select t.*, min(date) over (partition by client) as first_date
from t
group by client
) t
group by year(date), month(date);
Примечание: На основании ваших определений, это может подсчитатьКлиент дважды, если у них есть два заказа в первый месяц, они покупают.Возможно, вы захотите:
select year(date), month(date),
count(distinct case when first_date = date then client end) as new,
(count(distinct client) -
count(distinct case when first_date = date then client end)
) as repeat,
count(distinct client) as total
from (select t.*, min(date) over (partition by client) as first_date
from t
) t
group by year(date), month(date);
РЕДАКТИРОВАТЬ:
В более ранних версиях вы можете использовать group by
и join
для того же эффекта:
select year(date), month(date),
count(distinct case when first_date = date then client end) as new,
(count(distinct client) -
count(distinct case when first_date = date then client end)
) as repeat,
count(distinct client) as total
from t join
(select t.client, min(date) as first_date
from t
) c
using (client)
group by year(date), month(date);