-- 测试加上 layer = usersharedepth 条件
WITH t_rec AS (
    SELECT  dt, mid, subsessionid, headvideoid, vid, ts
            ,rootsourceid
            ,CASE WHEN rootsourceid = '' OR rootsourceid IS NULL THEN '内部' ELSE '外部' END AS in_out
            ,GET_JSON_OBJECT(extend,"$.extParams.userShareDepth") AS layer
    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 r
    LEFT JOIN t_vid_info v ON r.vid = v.vid
)
,t_head AS (
    SELECT  dt, mid, subsessionid, videoid
            ,UNIX_TIMESTAMP(`点击时间`) AS click_ts
            ,usersharedepth
            ,`merge二级品类` AS head_cate2
    FROM    loghubods.opengid_base_data
    WHERE   dt = "${start}"
)
-- 原始
,t_origin AS (
    SELECT  '1_原始曝光' AS step, COUNT(1) AS exp
    FROM    t_rec_with_cate
    WHERE   in_out = '内部' AND rec_cate2 = '人生忠告'
)
-- 当前方案：click_ts <= ts
,t_joined_v1 AS (
    SELECT  r.mid, r.subsessionid, r.headvideoid, r.vid, r.ts
            ,ROW_NUMBER() OVER (
                PARTITION BY r.mid, r.subsessionid, r.headvideoid, r.vid, r.ts
                ORDER BY h.click_ts DESC
            ) AS rn
    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
    AND     h.click_ts <= CAST(r.ts AS BIGINT)
    WHERE   r.in_out = '内部' AND r.rec_cate2 = '人生忠告'
)
,t_cnt_v1 AS (
    SELECT  '2_当前(click_ts<=ts)' AS step, COUNT(1) AS exp
    FROM    t_joined_v1 WHERE rn = 1
)
-- 新方案：click_ts <= ts + layer = usersharedepth
,t_joined_v2 AS (
    SELECT  r.mid, r.subsessionid, r.headvideoid, r.vid, r.ts
            ,ROW_NUMBER() OVER (
                PARTITION BY r.mid, r.subsessionid, r.headvideoid, r.vid, r.ts
                ORDER BY h.click_ts DESC
            ) AS rn
    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
    AND     h.click_ts <= CAST(r.ts AS BIGINT)
    AND     r.layer = h.usersharedepth  -- 新增条件
    WHERE   r.in_out = '内部' AND r.rec_cate2 = '人生忠告'
)
,t_cnt_v2 AS (
    SELECT  '3_新增(+layer=usersharedepth)' AS step, COUNT(1) AS exp
    FROM    t_joined_v2 WHERE rn = 1
)

SELECT * FROM t_origin
UNION ALL SELECT * FROM t_cnt_v1
UNION ALL SELECT * FROM t_cnt_v2
;
