-- 用 subsessionid + headvideoid 关联，验证是否解决膨胀问题
WITH t_rec_origin AS (
    SELECT  dt
            ,mid
            ,subsessionid
            ,headvideoid
            ,vid
            ,rootsourceid
            ,CASE WHEN rootsourceid = '' OR rootsourceid IS NULL THEN '内部' ELSE '外部' END AS in_out
    FROM    loghubods.dwd_recsys_alg_exposure_base_20250108
    WHERE   dt = "${start}"
    AND     apptype IN ('4','0')
    AND     page IN ("回流后沉浸页&内页feed","详情后沉浸页","首页feed","详情页")
)
,t_vid_info AS (
    SELECT  vid
            ,COALESCE(GET_JSON_OBJECT(feature,"$.merge_second_level_cate"),"unknown") AS rec_cate2
    FROM    (
                SELECT  vid, feature
                        ,ROW_NUMBER() OVER (PARTITION BY vid ORDER BY dt DESC,hh DESC ) AS rn
                FROM    loghubods.alg_vid_feature_basic_info
                WHERE   CONCAT(dt,hh) BETWEEN CONCAT("${start}","00") AND CONCAT("${start}","23")
            )
    WHERE   rn = 1
)
,t_rec_with_cate AS (
    SELECT  r.*, v.rec_cate2
    FROM    t_rec_origin r
    LEFT JOIN t_vid_info v ON r.vid = v.vid
)
-- 原始曝光数
,t_origin_cnt AS (
    SELECT  '1_原始曝光' AS step
            ,in_out
            ,rec_cate2
            ,COUNT(1) AS exp
            ,COUNT(DISTINCT CONCAT(mid, subsessionid)) AS subsession_cnt
    FROM    t_rec_with_cate
    WHERE   in_out = '内部'
    AND     rec_cate2 = '人生忠告'
    GROUP BY in_out, rec_cate2
)

-- 头部表
,t_head AS (
    SELECT  dt, mid, subsessionid, videoid, rootsourceid
            ,CASE WHEN rootsourceid = '' OR rootsourceid IS NULL THEN '内部' ELSE '外部' END AS head_in_out
            ,`merge二级品类` AS head_cate2
    FROM    loghubods.opengid_base_data
    WHERE   dt = "${start}"
)

-- 用 subsessionid + headvideoid 关联
,t_joined_v2 AS (
    SELECT  r.mid
            ,r.subsessionid
            ,r.headvideoid
            ,r.vid
            ,r.in_out
            ,r.rec_cate2
            ,h.videoid AS head_vid
            ,h.head_cate2
    FROM    t_rec_with_cate r
    LEFT JOIN t_head h
    ON      r.dt = h.dt
    AND     r.mid = h.mid
    AND     r.subsessionid = h.subsessionid
    AND     r.headvideoid = h.videoid  -- 增加 headvideoid 关联
    WHERE   r.in_out = '内部'
    AND     r.rec_cate2 = '人生忠告'
)
,t_joined_v2_cnt AS (
    SELECT  '2_Join_v2(+headvideoid)' AS step
            ,in_out
            ,rec_cate2
            ,COUNT(1) AS exp
            ,COUNT(DISTINCT CONCAT(mid, subsessionid)) AS subsession_cnt
    FROM    t_joined_v2
    GROUP BY in_out, rec_cate2
)

-- 汇总输出
SELECT * FROM t_origin_cnt
UNION ALL
SELECT * FROM t_joined_v2_cnt
;
