PRAGMA AnsiInForEmptyOrNullableItemsCollections;

$t = (
    SELECT 
        Week,
        SUM_IF(cube_revenue_w_cpa, commerce_type = 'commerce') AS Revenue,
        Place
    FROM hahn.`home/mcsanalytics/kalamkas/yan_cube_shortened_v1`
    WHERE fraud_type = 'normal'
    GROUP BY
        Week,
        IF(network_type = 'yan',
        CASE
            WHEN ownership_type = 'internal' THEN 'Внутренняя сеть'
            WHEN ownership_type = 'external' THEN 'Внешняя сеть'
            ELSE NULL
        END,
        'Поиск') AS Place
);

$k = (
    SELECT 
        t0.Week AS Week,
        t0.Revenue AS Revenue,
        t0.Place AS Place,
        CASE
            WHEN t1.Week_num <> 53 THEN t1.Week_num
            ELSE 52
        END AS Week_num,
        t1.Year AS Year
    FROM $t AS t0
    LEFT JOIN hahn.`home/mcsanalytics/kalamkas/week_num` AS t1
    ON t0.Week = CAST(t1.Start_of_week AS String)
);


SELECT DISTINCT
    t0.Week AS Week,
    t0.Place AS Place,
    t0.Revenue AS Revenue,
    t1.Revenue AS Prev_Rev
FROM $k AS t0
LEFT JOIN $k AS t1
ON t0.Place = t1.Place AND t0.Week_num = t1.Week_num
WHERE t0.Year - t1.Year = 1
ORDER BY Week DESC
