use hahn;

$week = ($date) -> {
    return DateTime::Format('%Y-%m-%d')(Datetime::MakeDate(DateTime::StartOfWeek(cast($date as Date))))
};

select
    week,
    count_if(days_missed > 1) as stopped_longer_1_day,
    avg_if(days_missed,days_missed > 0 ) as avg_day_missed,
    count_if(days_missed_wo_weekend > 1) as days_missed_wo_weekend,
    count_if(costs > 0) as count_active_clients
from
    (
        select
            week,
            curr_counterparty_id,
            sum(day_is_missed_wo_fut) as days_missed,
            sum(cost_rub_wo_nds) as costs,
            sum_if(day_is_missed_wo_fut, DateTime::GetDayOfWeek(date_day) <= 5) as days_missed_wo_weekend
        from `//home/vipplanners/dashboard_paused_clients/counterparty_daily`
        where day_is_missed_wo_fut = 1 or cost_rub_wo_nds > 0
        group by
            $week(date_day) as week,
            curr_counterparty_id
    )
where costs > 0
group by week
