USE hahn;
--PRAGMA yt.ExternalTx = '25f2b-326575-3fe0001-bef2';
$week = ($day) -> {
    return DateTime::Format("%Y-%m-%d")(DateTime::StartOfWeek(cast($day as Date)))
};

SELECT Week,
MEDIAN(First_click_time) as First_click_time,
App_type
FROM (
SELECT 
    $week(create_day) as Week,
     IF(bssynced_status_to_first_click_h < 24 * 7, bssynced_status_to_first_click_h, NULL) AS First_click_time,
    IF(app_type = 'Мастер кампаний', 'UC', 'Все, кроме UC') AS App_type
FROM `//home/operanalytics/regular/WeeklyPack/ttt`
WHERE 1 = 1
AND IF(app_type = 'Мастер кампаний' AND CAST(create_day AS Date) < Date('2021-03-08'), 0, 1) = 1
AND has_start_time IN ('Без отложенного старта')
AND is_fraud IN ('Не Фрод')
AND client_tier IN ('SB', 'SMB CENTER', 'SMB REGIONS')
    )
GROUP BY  Week, App_type
ORDER BY Week DESC
--INTO RESULT `Time_to_Target_to_Click_SMB`