/* ADCAMPAIGN-107: обзор клиента

Данные для дашборда

Разделы:
- статистика по клиенту за 30 дней
- показатели настроек
- информация из CRM
- основные регионы показов
*/
USE hahn;

-- статистика по клиенту за 30 дней
$client_tables = (
SELECT TOP_BY(Path, CAST(TableName(Path) AS Date), 30)
FROM FOLDER(`//home/comdep-cubes/direct/production/hypercubes/clients`)
);

-- показатели настроек
$last_table = (
SELECT MAX_BY(Path, CAST(TableName(Path) AS Date))
FROM FOLDER(`home/comdep-cubes/direct/production/hypercubes/clients`)
);

-- основные регионы показов
$client_geo_tables = (
SELECT TOP_BY(Path, CAST(TableName(Path) AS Date), 30)
FROM FOLDER(`//home/comdep-cubes/direct/production/cube`)
);

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_total` WITH TRUNCATE
SELECT
  client_id
, SUM(shows) ?? 0 AS shows
, SUM(clicks) ?? 0 AS clicks
, SUM(cost) ?? 0 AS cost
, SUM(search_shows) ?? 0 AS search_shows
, SUM(search_clicks) ?? 0 AS search_clicks
, SUM(search_cost) ?? 0. AS search_cost
, SUM(network_shows) ?? 0 AS network_shows
, SUM(network_clicks) ?? 0 AS network_clicks
, SUM(network_cost) ?? 0. AS network_cost
FROM EACH($client_tables)
GROUP BY client_id
HAVING SUM(shows) > 0
ORDER BY client_id
; COMMIT;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/counterparty_total` WITH TRUNCATE
SELECT
  counterparty
, SUM(shows) AS shows
, SUM(clicks) AS clicks
, SUM(cost) AS cost
, SUM(search_shows) AS search_shows
, SUM(search_clicks) AS search_clicks
, SUM(search_cost) AS search_cost
, SUM(network_shows) AS network_shows
, SUM(network_clicks) AS network_clicks
, SUM(network_cost) AS network_cost
FROM `//home/vipplanners/insights/data/dash_client_report/client_total` AS s
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest` AS crm
  ON s.client_id = crm.client_id
GROUP BY curr_counterparty_name AS counterparty
HAVING SUM(shows) > 0
ORDER BY counterparty
;

-- https://wiki.yandex-team.ru/sales/бизнес-аналитика/comdep-client-hypercubes-descriprion/description-table/
INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_metrics` WITH TRUNCATE
SELECT
  client_id
, cube_date ?? "" AS cube_date
-- Типы кампаний
, Coalesce(search_enabled_text_groups, 0) > 0  AS search_enabled
, Coalesce(context_enabled_text_groups, 0) > 0 AS context_enabled
, Coalesce(context_enabled_text_groups, 0) + Coalesce(search_enabled_text_groups, 0) > Coalesce(text_groups, 0) AS search_context_enabled
, Coalesce(search_enabled_mobile_content_groups, 0) > 0 AS search_enabled_mobile
, Coalesce(context_enabled_mobile_content_groups, 0) > 0 AS context_enabled_mobile
, Coalesce(search_enabled_mobile_content_groups, 0) + Coalesce(context_enabled_mobile_content_groups, 0) > Coalesce(mobile_content_groups, 0)
  AS search_context_enabled_mobile
, Coalesce(smart_orders, 0) > 0 AS smart_orders_enabled
, Coalesce(dynamic_orders, 0) > 0 AS dynamic_orders_enabled
, Coalesce(cpm_orders, 0) > 0 AS cpm_orders_enabled
, Coalesce(cpm_deals_orders, 0) > 0 AS cpm_deals_orders_enabled
-- Настройки кампаний
, orders ?? 0 AS orders  -- Всего не архивных кампаний
, search_enabled_text_orders ?? 0 AS search_enabled_text_orders
, timetarget_orders ?? 0 AS timetarget_orders
-- timetarget_orders / orders
, timetarget_orders_pct ?? 0. AS timetarget_orders_pct  -- использование временного таргетинга
, Coalesce(retargeting_multipliers_groups, 0) > 0 AS retargeting_multipliers_enabled  -- Корректировка целевой аудитории
, Coalesce(demography_multipliers_groups, 0) > 0 AS demography_multipliers_enabled  -- Корректировка пол-возраст
, Coalesce(mobile_multipliers_groups, 0) > 0 AS mobile_multipliers_enabled  -- Корректировка мобильности
, day_budget_orders ?? 0 AS day_budget_orders
, day_budget_orders_pct ?? 0. AS day_budget_orders_pct -- Процент кампаний, ограничение дневного бюджета
, smart_orders ?? 0 AS smart_orders
, autobudget_orders ?? 0 AS autobudget_orders
-- (autobudget_orders - smart_orders) / (orders - smart_orders)
, autobudget_orders_pct ?? 0. AS autobudget_orders_pct -- Процент кампаний с автостратегией
, max_bid_capped_orders ?? 0 AS max_bid_capped_orders
-- max_bid_capped_orders / autobudget_orders
, max_bid_capped_orders_pct ?? 0. AS max_bid_capped_orders_pct  -- Процент кампаний с ограничением максимальной ставки
, good_domains_disabled_orders ?? 0 AS good_domains_disabled_orders  -- Количество кампаний с заблокированные крупными площадками
, metrika_orders ?? 0 AS metrika_orders -- Количество кампаний с счетчиками метрики
, mobile_content_orders ?? 0 AS mobile_content_orders
, metrika_orders_pct ?? 0. AS metrika_orders_pct  -- Процент кампаний с счетчиками метрики
-- Условия показа
, Coalesce(retargeting_conditions_groups, 0) > 0 AS retargeting_conditions_enabled  -- Ретаргетинг
, Coalesce(audience_retargeting_conditions_groups, 0) > 0 AS audience_retargeting_conditions_enabled  -- Подбор аудитории
, Coalesce(relevance_match_groups, 0) > 0 AS relevance_match_enabled  -- Автотаргетинг
, drf_orders ?? 0 AS drf_orders
-- drf_orders / search_enabled_text_orders
, drf_orders_pct ?? 0. AS  drf_orders_pct  -- ДРФ
-- объявления
, text_banners ?? 0 AS text_banners
, turbolanding_banners ?? 0 AS turbolanding_banners
-- turbolanding_banners / text_banners
, turbolanding_banners_pct ?? 1. AS turbolanding_banners_pct -- процент баннеров с турбо-страницами
, dynamic_banners ?? 0 AS dynamic_banners
, vcard_banners ?? 0 AS vcard_banners
-- vcard_banners / (text_banners + dynamic_banners)
, vcard_banners_pct ?? 1. AS vcard_banners_pct -- процент баннеров с визиткой
, sitelinks_banners ?? 0 AS sitelinks_banners
-- sitelinks_banners / (text_banners + dynamic_banners)
, sitelinks_banners_pct ?? 1. AS sitelinks_banners_pct  -- процент баннеров с быстрыми ссылками (БС)
, sitelinks_with_description_banners ?? 0 AS sitelinks_with_description_banners
, search_enabled_text_banners ?? 0 AS search_enabled_text_banners
-- sitelinks_with_description_banners / (search_enabled_text_banners + dynamic_banners)
, sitelinks_with_description_banners_pct ?? 1. AS sitelinks_with_description_banners_pct  -- Процент баннероы с БС с описаниями
, callout_banners ?? 0 AS callout_banners
-- callout_banners / (text_banners + dynamic_banners)
, callout_banners_pct ?? 1. AS callout_banners_pct  -- процент баннеров с уточенениями
, display_href_banners ?? 0 AS display_href_banners
-- display_href_banners / text_banners
, display_href_banners_pct ?? 1. AS display_href_banners_pct  -- процент баннеров с отображаемой ссылкой
, title_extension_banners AS title_extension_banners
-- title_extension_banners / text_banners
, title_extension_banners_pct ?? 1. AS title_extension_banners_pct -- процент баннеров второй заголовок
, video_addition_banners ?? 0 AS video_addition_banners
, context_enabled_text_banners ?? 0 AS context_enabled_text_banners
-- video_addition_banners / context_enabled_text_banners
, video_addition_banners_pct ?? 1. AS video_addition_banners_pct  -- процент баннеров с видеодополнениями
, image_banners ?? 0 AS image_banners
, context_enabled_mobile_content_banners ?? 0 AS context_enabled_mobile_content_banners
-- image_banners / (context_enabled_text_banners + context_enabled_mobile_content_banners)
, image_banners_pct ?? 1. AS image_banners_pct  -- процент баннеров с картинками
, groups ?? 0 AS groups
, with_image_ad_groups ?? 0 AS with_image_ad_groups
, context_enabled_text_groups ?? 0 AS context_enabled_text_groups
, context_enabled_mobile_content_groups ?? 0 AS context_enabled_mobile_content_groups
-- with_image_ad_groups / (context_enabled_text_groups + context_enabled_mobile_content_groups)
, with_image_ad_groups_pct ?? 1. AS with_image_ad_groups_pct  -- процент групп с графическими объявлениями
, with_cpc_video_groups ?? 0 AS with_cpc_video_groups
-- with_cpc_video_groups / context_enabled_text_groups
, with_cpc_video_groups_pct ?? 1. AS with_cpc_video_groups_pct  -- процент групп с видеообъявлениями
, with_mobile_groups ?? 0 AS with_mobile_groups
, text_groups ?? 0 AS text_groups
-- with_mobile_groups / text_groups
, with_mobile_groups_pct ?? 1. AS with_mobile_groups_pct  -- процент групп с мобильными объявлениями
, with_desktop_groups ?? 0 AS with_desktop_groups
-- with_desktop_groups / text_groups
, with_desktop_groups_pct ?? 1. AS with_desktop_groups_pct  -- процент групп с десктопными объявлениями
, with_wide_image_groups ?? 0 AS with_wide_image_groups
-- with_wide_image_groups / (context_enabled_text_groups + context_enabled_mobile_content_groups)
, with_wide_image_groups_pct ?? 1. AS with_wide_image_groups_pct  -- процент групп с широкоформатными картинками
FROM CONCAT($last_table)
ORDER BY client_id
; COMMIT;

PRAGMA ClassicDivision = "false";

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/counterparty_metrics` WITH TRUNCATE
SELECT
  counterparty
, SOME(s.cube_date) AS cube_date
-- Типы кампаний
, MAX(s.search_enabled) AS search_enabled
, MAX(s.context_enabled) AS context_enabled
, MAX(s.search_context_enabled) AS search_context_enabled
, MAX(s.search_enabled_mobile) AS search_enabled_mobile
, MAX(s.context_enabled_mobile) AS context_enabled_mobile
, MAX(s.search_context_enabled_mobile) AS search_context_enabled_mobile
, MAX(s.smart_orders_enabled) AS smart_orders_enabled
, MAX(s.dynamic_orders_enabled) AS dynamic_orders_enabled
, MAX(s.cpm_orders_enabled) AS cpm_orders_enabled
, MAX(s.cpm_deals_orders_enabled) AS cpm_deals_orders_enabled
-- Настройки кампаний
, COUNT(DISTINCT s.client_id) AS client_ids
, SUM(s.orders) AS orders  -- Всего не архивных кампаний
, Coalesce(SUM(s.timetarget_orders) / SUM(s.orders), 0.) AS timetarget_orders_pct  -- использование временного таргетинга
, MAX(s.retargeting_multipliers_enabled) AS retargeting_multipliers_enabled  -- Корректировка целевой аудитории
, MAX(s.demography_multipliers_enabled) AS demography_multipliers_enabled  -- Корректировка пол-возраст
, MAX(s.mobile_multipliers_enabled) AS mobile_multipliers_enabled  -- Корректировка мобильности
, Coalesce(SUM(s.day_budget_orders) / SUM(s.orders), 0.) AS day_budget_orders_pct -- Процент кампаний, ограничение дневного бюджета
, Coalesce(SUM(Coalesce(s.autobudget_orders, 0) - Coalesce(s.smart_orders, 0)) / SUM(s.orders - Coalesce(s.smart_orders, 0)), 0.) AS autobudget_orders_pct -- Процент кампаний с автостратегией
, NANVL(Coalesce(SUM(s.max_bid_capped_orders ?? 0) / SUM(s.autobudget_orders ?? 0), 0.), 0.) AS max_bid_capped_orders_pct  -- Процент кампаний с ограничением максимальной ставки
, SUM(good_domains_disabled_orders) ?? 0 AS good_domains_disabled_orders  -- Количество кампаний с заблокированные крупными площадками
, SUM(metrika_orders) ?? 0 AS metrika_orders -- Количество кампаний с счетчиками метрики
, Coalesce(SUM(s.metrika_orders ?? 0) / SUM(s.orders - Coalesce(s.mobile_content_orders, 0)), 0.) AS metrika_orders_pct  -- Процент кампаний с счетчиками метрики
-- Условия показа
, MAX(s.retargeting_conditions_enabled) AS retargeting_conditions_enabled  -- Ретаргетинг
, MAX(s.audience_retargeting_conditions_enabled) AS audience_retargeting_conditions_enabled  -- Подбор аудитории
, MAX(s.relevance_match_enabled) AS relevance_match_enabled  -- Автотаргетинг
, NANVL(Coalesce(SUM(s.orders) / SUM(s.search_enabled_text_orders ?? 0), 0.), 0.) AS drf_orders_pct  -- ДРФ
-- объявления
, NANVL(Coalesce(SUM(s.turbolanding_banners ?? 0) / SUM(s.text_banners ?? 0), 1.), 1.) AS turbolanding_banners_pct -- процент баннеров с турбо-страницами
, NANVL(Coalesce(SUM(s.vcard_banners ?? 0) / SUM(Coalesce(s.text_banners, 0) + Coalesce(s.dynamic_banners, 0)), 1.), 1.) AS vcard_banners_pct  -- процент баннеров с визиткой
, NANVL(Coalesce(SUM(s.sitelinks_banners ?? 0) / SUM(Coalesce(s.text_banners, 0) + Coalesce(s.dynamic_banners, 0)), 1.), 1.) AS sitelinks_banners_pct  -- процент баннеров с быстрыми ссылками (БС)
, NANVL(Coalesce(SUM(s.sitelinks_with_description_banners ?? 0) / SUM(Coalesce(s.search_enabled_text_banners, 0) + Coalesce(s.dynamic_banners, 0)), 1.), 1.) AS sitelinks_with_description_banners_pct  -- Процент баннероы с БС с описаниями
, NANVL(Coalesce(SUM(s.callout_banners ?? 0) / SUM(Coalesce(s.text_banners, 0) + Coalesce(s.dynamic_banners, 0)), 1.), 1.) AS callout_banners_pct  -- процент баннеров с уточенениями
, NANVL(Coalesce(SUM(s.display_href_banners ?? 0) / SUM(s.text_banners ?? 0), 1.), 1.) AS display_href_banners_pct  -- процент баннеров с отображаемой ссылкой
, NANVL(Coalesce(SUM(s.title_extension_banners ?? 0) / SUM(s.text_banners ?? 0), 1.), 1.) AS title_extension_banners_pct -- процент баннеров второй заголовок
, NANVL(Coalesce(SUM(s.video_addition_banners ?? 0) / SUM(s.context_enabled_text_banners ?? 0), 1.), 1.0) AS video_addition_banners_pct  -- процент баннеров с видеодополнениями
, NANVL(Coalesce(SUM(s.image_banners ?? 0) / SUM(Coalesce(s.context_enabled_text_banners, 0) + Coalesce(s.context_enabled_mobile_content_banners, 0)), 1.), 1.) AS image_banners_pct  -- процент баннеров с картинками
, NANVL(Coalesce(SUM(s.with_image_ad_groups ?? 0) / SUM(Coalesce(s.context_enabled_text_groups, 0) + Coalesce(s.context_enabled_mobile_content_groups, 0)), 1.), 1.) AS with_image_ad_groups_pct  -- процент групп с графическими объявлениями
, NANVL(Coalesce(SUM(s.with_cpc_video_groups ?? 0) / SUM(s.context_enabled_text_groups ?? 0), 1.), 1.) AS with_cpc_video_groups_pct  -- процент групп с видеообъявлениями
-- with_mobile_groups / text_groups
, NANVL(Coalesce(SUM(s.with_mobile_groups ?? 0) / SUM(s.text_groups ?? 0), 1.), 1.) AS with_mobile_groups_pct  -- процент групп с мобильными объявлениями
, NANVL(Coalesce(SUM(s.with_desktop_groups ?? 0) / SUM(s.text_groups?? 0), 1.), 1.) AS with_desktop_groups_pct  -- процент групп с десктопными объявлениями
-- with_wide_image_groups / (context_enabled_text_groups + context_enabled_mobile_content_groups)
, NANVL(Coalesce(SUM(s.with_wide_image_groups ?? 0) / SUM(Coalesce(s.context_enabled_text_groups, 0) + Coalesce(s.context_enabled_mobile_content_groups, 0)), 1.), 1.) AS with_wide_image_groups_pct  -- процент групп с широкоформатными картинками
FROM `//home/vipplanners/insights/data/dash_client_report/client_metrics` AS s
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest` AS crm
  ON s.client_id = crm.client_id
GROUP BY crm.curr_counterparty_name AS counterparty
; COMMIT;

PRAGMA ClassicDivision = "true";


INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_crm` WITH TRUNCATE
SELECT 
  client_id
, SOME(curr_manager_name) ?? "Не назначен" AS manager_name
, SOME(curr_manager_domain_login) ?? "Неизвестно" AS manager_login
, SOME(curr_client_tier) ?? "Неизвестно" AS tier
, SOME(curr_counterparty_name) ?? "Неизвестно" AS counterparty_name
, SOME(curr_client_main_domain) ?? "Неизвестно" AS main_domain
, SOME(curr_industry) ?? "Неизвестно" AS industry
FROM `home/comdep-analytics/public/client_tiers/fact/latest`
GROUP BY client_id
ORDER BY client_id
;


$find_region_name = ($id, $type) -> {
-- https://doc.yandex-team.ru/lib/libgeobase5/concepts/region-types.html
-- https://doc.yandex-team.ru/lib/libgeobase5/concepts/interfaces-cplusplus-structures.html#ariaid-title15
  $type_id = AsDict(
    ("continent", 1),
    ("world_part", 2),
    ("country", 3),
    ("district", 4),
    ("region", 5),
    ("city", 6),
    ("town", 7),
  );
  $region = Geo::RoundRegionById(CAST($id AS Int32), $type);
  RETURN IF($region.type == $type_id[$type], $region.name ?? 'Unknown', Nothing(String?));
};

-- Регионы
INSERT INTO @client_geo WITH TRUNCATE
SELECT 
  s.client_id AS client_id
, crm.curr_counterparty_name AS counterparty
, s.cost_rub_wo_nds AS cost
, s.banner_group_has_geo_targeting AS banner_group_has_geo_targeting
, s.campaign_has_geo_targeting AS campaign_has_geo_targeting
, s.campaign_is_extended_geo_disabled AS campaign_is_extended_geo_disabled
, s.region_id AS region_id
, $find_region_name(s.region_id, "city") AS city
, $find_region_name(s.region_id, "district") AS district
, $find_region_name(s.region_id, "country") AS country
FROM EACH($client_geo_tables) AS s
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest` AS crm
  ON s.client_id = crm.client_id
WHERE s.shows > 0
; COMMIT;

INSERT INTO @client_geo_total WITH TRUNCATE
SELECT
  client_id
, SUM(cost) AS cost
FROM @client_geo
GROUP BY client_id
HAVING SUM(cost) > 0
; 
INSERT INTO @counterparty_geo_total WITH TRUNCATE
SELECT
  counterparty
, SUM(cost) AS cost
FROM @client_geo
GROUP BY counterparty
HAVING SUM(cost) > 0
; 
COMMIT;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_geo_city` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.client_id AS client_id
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      client_id
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE city > ""
    GROUP BY client_id, city AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @client_geo_total AS total
    USING (client_id)
  WINDOW client_region_w AS (
    PARTITION BY region.client_id
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  client_id
, region_rank
;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/counterparty_geo_city` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.counterparty AS counterparty
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      counterparty
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE city > ""
    GROUP BY counterparty, city AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @counterparty_geo_total AS total
    USING (counterparty)
  WINDOW client_region_w AS (
    PARTITION BY region.counterparty
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  counterparty
, region_rank
;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_geo_district` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.client_id AS client_id
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      client_id
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE district > ""
    GROUP BY client_id, district AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @client_geo_total AS total
    USING (client_id)
  WINDOW client_region_w AS (
    PARTITION BY region.client_id
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  client_id
, region_rank
;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/counterparty_geo_district` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.counterparty AS counterparty
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      counterparty
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE district > ""
    GROUP BY counterparty, district AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @counterparty_geo_total AS total
    USING (counterparty)
  WINDOW client_region_w AS (
    PARTITION BY region.counterparty
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  counterparty
, region_rank
;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/client_geo_country` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.client_id AS client_id
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      client_id
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE country > ""
    GROUP BY client_id, country AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @client_geo_total AS total
    USING (client_id)
  WINDOW client_region_w AS (
    PARTITION BY region.client_id
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  client_id
, region_rank
;

INSERT INTO `//home/vipplanners/insights/data/dash_client_report/counterparty_geo_country` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    region.counterparty AS counterparty
  , region.name AS region_name
  , Coalesce(region.cost / total.cost, 0.) AS region_share
  , ROW_NUMBER() OVER client_region_w AS region_rank
  FROM (
    SELECT
      counterparty
    , name
    , SUM(cost) AS cost
    FROM @client_geo
    WHERE country > ""
    GROUP BY counterparty, country AS name
    HAVING SUM(cost) > 0
  ) AS region
  LEFT JOIN @counterparty_geo_total AS total
    USING (counterparty)
  WINDOW client_region_w AS (
    PARTITION BY region.counterparty
    ORDER BY region.cost DESC
  )
)
WHERE region_rank <= 10
ORDER BY
  counterparty
, region_rank
;
