-- tm_building_user_wifi_m 楼宇 WiFi 指标月表 核心计算逻辑 (标准契约版)
-- 计算侧：HiveSQL
-- 数据源：ODS OTT（WiFi 指标）
-- 输出：楼宇 WiFi 用户数、市场份额、信号强度

-- 参数设置
-- SET hivevar:year_month='2026-05';

-- Step 1: 创建临时表关联楼宇信息
DROP TABLE IF EXISTS tmp_tm_building_user_wifi_m;
CREATE TABLE tmp_tm_building_user_wifi_m AS
SELECT
    '${hivevar:year_month}' AS year_month,
    b.building_id,
    b.building_name,
    b.building_type,
    b.provincecode,
    b.province_name,
    b.citycode,
    b.city_name,
    b.districtcode,
    b.district_name,
    'telecom' AS operator_name,
    -- 使用 LATERAL VIEW EXPLODE 展开数组后统计去重用户
    approx_count_distinct(CASE WHEN w.wifi_name IS NOT NULL THEN exploded_device_id END) AS wifi_total_user_count,
    approx_count_distinct(CASE WHEN w.wifi_name = 'ChinaNet' THEN exploded_device_id END) AS wifi_user_count,
    -- WiFi 市场份额
    CASE
        WHEN approx_count_distinct(CASE WHEN w.wifi_name IS NOT NULL THEN exploded_device_id END) > 0
        THEN approx_count_distinct(CASE WHEN w.wifi_name = 'ChinaNet' THEN exploded_device_id END) * 1.0 /
             approx_count_distinct(CASE WHEN w.wifi_name IS NOT NULL THEN exploded_device_id END)
        ELSE NULL
    END AS wifi_market_share,
    AVG(w.signal_strength) AS wifi_signal_strength
FROM (
    SELECT building_id, building_name, building_type,
           provincecode, province_name, citycode, city_name,
           districtcode, district_name
    FROM td_building
) b
LEFT JOIN (
    SELECT building_id, wifi_name, device_id_list, signal_strength
    FROM ODS_OTT_WIFI
    WHERE year_month = '${hivevar:year_month}'
      AND operator_name = 'telecom'
) w ON b.building_id = w.building_id
LATERAL VIEW EXPLODE(w.device_id_list) t AS exploded_device_id
GROUP BY
    b.building_id, b.building_name, b.building_type,
    b.provincecode, b.province_name, b.citycode, b.city_name,
    b.districtcode, b.district_name
;

-- Step 2: 验证数据
-- SELECT COUNT(*) FROM tmp_tm_building_user_wifi_m;
-- SELECT year_month, building_id, wifi_total_user_count, wifi_user_count, wifi_market_share
-- FROM tmp_tm_building_user_wifi_m LIMIT 10;
