SELECT
country_id,
toStartOfDay(max(ts), 'Europe/Kyiv') AS as_of_date,
hangup_rate,
all_answered
from
(select
ts,
country_id,
round((100 * QUEUE_HANGUP/ all_answered), 2) as hangup_rate,
all_answered
from
(
SELECT
toDate(ts) AS ts,
co.country_id,
CASE
WHEN count() > 0 THEN sum(CASE WHEN v.client_call_status = 'QUEUE_HANGUP' THEN 1 ELSE 0 END)
ELSE NULL
END as QUEUE_HANGUP,
CASE
WHEN count() > 0 THEN sum(CASE WHEN v.client_call_status = 'ANSWERED' THEN 1 ELSE 0 END)
ELSE NULL
END as ANSWERED,
CASE
WHEN count() > 0 THEN sum(CASE WHEN v.client_call_status in ('ANSWERED','QUEUE_HANGUP') THEN 1 ELSE 0 END)
ELSE NULL
END as all_answered
FROM vt_tm_cdrs v
join crm_orders co on v.order_id = co.id
where
co.created_at >= date(now(), 'Europe/Kyiv') - interval 2 day and co.created_at <= date(now(), 'Europe/Kyiv')
and v.ts >= date(now(), 'Europe/Kyiv') - interval 2 day and v.ts <= date(now(), 'Europe/Kyiv')
GROUP BY
ts, country_id
ORDER BY
ts, country_id ASC
) q
) q2
GROUP BY
country_id, toStartOfDay(ts), hangup_rate, all_answered;