use hahn;
$month_st=($date)-> { 
RETURN DateTime::Format("%Y-%m-%d")(Datetime::MakeDate(DateTime::StartOfMonth(CAST($date as Date))));};

    SELECT
        month,
        sum_if(`money_and_forec`, w.client_type = 'Клиент' and w.agency_type = 'Агентство' or  client_type = 'Агентство') AS agencies_cost,
        sum(`money_and_forec`) AS cost
    FROM
        hahn.`statbox/cube/daily/comdep/cd_reporting/cd_all_with_tiers`AS b
    LEFT JOIN
        `//home/comdep-analytics/public/client_tiers/fact/latest` AS w
    ON
        w.client_id = b.clientid
    WHERE
        'Общая выручка' IN `product_list` and `currency`='rur' and period>='2019-01-01' and scale='months'
        group compact by
        $month_st(period) as month;
