Use hahn;
$week = ($date) -> {
    return DateTime::Format('%Y-%m-%d')(Datetime::MakeDate(DateTime::StartOfWeek(cast($date as Date))))
};
$capture_cluster = Re2::Capture("([0-9]*)$");
$find_day=($date, $delta_day) ->{RETURN CAST(CAST(CAST($date as Date)+DateTime::IntervalFromDays($delta_day) as Date) as String)};
$get_cluster_group=($clt_nmb)->{RETURN
    CASE WHEN $clt_nmb == 0
    THEN 'Сильно снизившие с небольшим возвратом (-50%)'
    WHEN $clt_nmb = 1
    THEN 'Стабильные (0%)'
    WHEN $clt_nmb = 3
    THEN 'Резко снизившие (-40-60%)'
    WHEN $clt_nmb = 4
    THEN 'Выросшие с возвратом (100%)'
    WHEN $clt_nmb = 5
    THEN 'Умеренно снизившие с недельной сезонностью (-20%)'
    WHEN  $clt_nmb = 6
    THEN 'Умеренно снизившие (-20%)'
    ELSE 'Без кластера'
    END};
        
$fact=
SELECT
    cluster,
    cluster_group,
    week,
    sum(`value`) as costs_fact
FROM hahn.`home/analyticskeymetrics/export/covid19_forecast/money/fact/latest`
 GROUP BY $week($find_day(`date`, 1)) as week
 , cluster
 , $get_cluster_group(cast($capture_cluster(cluster)._0 as Int64)) as cluster_group;
;

$forecast=
SELECT
    week,
    cluster_group,
    cluster,
    sum(`value`) as costs_forecast
FROM hahn.`home/analyticskeymetrics/export/covid19_forecast/money/forecast/2020-06-09`
WHERE scenario='pessimistic'
 GROUP BY $week($find_day(`date`, 1)) as week
 , `cluster`
 , $get_cluster_group(cast($capture_cluster(cluster)._0 as Int64)) as cluster_group;




        
SELECT 
week,
cluster_group,
cluster,
sum(frc.`costs_forecast`) as costs_forecast,
sum(fct.`costs_fact`) as costs_fact,
sum(yoy.`costs_fact`) as costs_yoy
FROM
$forecast as frc
FULL JOIN $fact as fct ON frc.week=fct.week and frc.cluster=fct.cluster
LEFT JOIN  $fact as yoy ON yoy.week=$find_day(fct.week, -364) and yoy.cluster=fct.cluster
GROUP BY 
nvl(fct.cluster, frc.cluster) as cluster,
nvl(fct.cluster_group,frc.cluster_group) as cluster_group,
nvl(fct.week, frc.week) as week