-- 测试三类人群：内部/外部0层/外部裂变，加上 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_rec_with_crowd AS (
    SELECT  r.*
            ,CASE   WHEN in_out = '内部' THEN '内部'
                    WHEN layer = '0' THEN '外部0层'
                    WHEN CAST(layer AS INT) > 0 THEN '外部裂变'
                    ELSE '其他'
            END AS crowd
    FROM    t_rec r
)
,t_head AS (
    SELECT  dt, mid, subsessionid, videoid
            ,UNIX_TIMESTAMP(`点击时间`) AS click_ts
            ,usersharedepth
    FROM    loghubods.opengid_base_data
    WHERE   dt = "${start}"
)
-- 原始曝光（按人群）
,t_origin AS (
    SELECT  crowd, '1_原始曝光' AS step, COUNT(1) AS exp
    FROM    t_rec_with_crowd
    WHERE   crowd <> '其他'
    GROUP BY crowd
)
-- 当前方案：click_ts <= ts
,t_joined_v1 AS (
    SELECT  r.crowd, 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_crowd 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.crowd <> '其他'
)
,t_cnt_v1 AS (
    SELECT  crowd, '2_当前(click_ts<=ts)' AS step, COUNT(1) AS exp
    FROM    t_joined_v1 WHERE rn = 1
    GROUP BY crowd
)
-- 新方案：click_ts <= ts + layer = usersharedepth
,t_joined_v2 AS (
    SELECT  r.crowd, 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_crowd 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.crowd <> '其他'
)
,t_cnt_v2 AS (
    SELECT  crowd, '3_新增(+layer=depth)' AS step, COUNT(1) AS exp
    FROM    t_joined_v2 WHERE rn = 1
    GROUP BY crowd
)

SELECT * FROM t_origin
UNION ALL SELECT * FROM t_cnt_v1
UNION ALL SELECT * FROM t_cnt_v2
ORDER BY crowd, step
;
