-- OPERANALYTICS-951
-- список клиентов отказавшихся от смартбаннеров
USE hahn;

$LAST = (SELECT MAX(eventdate) FROM `//home/vipplanners/dashboard_smartbanners/cube/client_daily`);
$D30 = $LAST - Interval("P30D");
$D90 = $LAST - Interval("P90D");

$curr_client_stat = (
SELECT
  s.*
, DateTime::ToDays($LAST - last_cost_date) AS last_cost_age_days
, CASE
    WHEN cost_rub_wo_nds_30d = 0 THEN '=0'
    WHEN cost_rub_wo_nds_30d < 100 THEN '(0,100]'
    WHEN cost_rub_wo_nds_30d < 1000 THEN '(100,1000]'
    ELSE '1000+'
  END AS cost_rub_wo_nds_30d_type
FROM (
  SELECT
    ClientID
  , MAX(eventdate) AS last_cost_date
  , $LAST AS update_date
  , SUM_IF(cost_rub_wo_nds, eventdate BETWEEN $D30 AND $LAST) ?? 0 AS cost_rub_wo_nds_30d
  , SUM_IF(cost_rub_wo_nds, eventdate BETWEEN $D90 AND $LAST) ?? 0 AS cost_rub_wo_nds_90d
  FROM `//home/vipplanners/dashboard_smartbanners/cube/client_daily`
  WHERE cost_rub_wo_nds > 0
  GROUP BY ClientID
) AS s
);

INSERT INTO `//home/vipplanners/dashboard_smartbanners/cube/client_last_activity` WITH TRUNCATE
SELECT
  s.*
, crm.curr_client_main_domain AS curr_client_main_domain
, crm.curr_counterparty_reporting_tier.name AS curr_client_tier
, crm.client_login AS client_login
FROM $curr_client_stat AS s
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest_v2` AS crm
  ON s.ClientID = crm.client_id
ORDER BY ClientID
;