-- 单日查询：按天增量获取数据
-- 参数: ${dt} - 日期，格式 YYYYMMDD
WITH t_rec AS (
    SELECT  dt
            ,mid
            ,subsessionid
            ,headvideoid
            ,vid AS rec_vid
            ,ts
            ,CASE WHEN rootsourceid = '' OR rootsourceid IS NULL THEN '内部' ELSE '外部' END AS in_out
            ,page
            ,CASE   WHEN page IN ("回流后沉浸页&内页feed","详情后沉浸页","首页feed","详情页") THEN "推荐"
                    WHEN page IN ("回流页","其他") THEN "非推荐"
                    ELSE "其他"
            END AS page_rec
            ,share_cnt
            ,return_n_uv
            ,new_exposure_cnt
            ,GET_JSON_OBJECT(extend,"$.extParams.userShareDepth") AS layer
    FROM    loghubods.dwd_recsys_alg_exposure_base_20250108
    WHERE   dt = "${dt}"
    AND     apptype IN ('4','0')
    AND     page IN ("回流后沉浸页&内页feed","详情后沉浸页","首页feed","详情页","回流页","其他")
)
,t_vid_info AS (
    -- 视频品类信息表（取当天及前后1天的数据，确保覆盖）
    SELECT  vid
            ,COALESCE(GET_JSON_OBJECT(feature,"$.merge_second_level_cate"),"unknown") AS 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(TO_CHAR(DATEADD(TO_DATE("${dt}",'yyyymmdd'),-1,'dd'),'yyyymmdd'),"00")
                                          AND CONCAT(TO_CHAR(DATEADD(TO_DATE("${dt}",'yyyymmdd'),1,'dd'),'yyyymmdd'),"23")
            )
    WHERE   rn = 1
)
,t_joined AS (
    SELECT  r.dt
            ,CASE   WHEN r.in_out = '内部' THEN '内部'
                    WHEN r.layer = '0' THEN '外部0层'
                    WHEN CAST(r.layer AS INT) > 0 THEN '外部裂变'
                    ELSE '其他'
            END AS crowd
            ,CASE   WHEN r.headvideoid IS NULL OR r.headvideoid = '' THEN 'headvideoid为空'
                    WHEN h.cate2 IS NULL THEN '未匹配品类'
                    ELSE h.cate2
            END AS head_cate2
            ,COALESCE(v.cate2, 'unknown') AS rec_cate2
            ,r.share_cnt
            ,r.return_n_uv
            ,r.new_exposure_cnt
    FROM    t_rec r
    LEFT JOIN t_vid_info h ON r.headvideoid = h.vid
    LEFT JOIN t_vid_info v ON r.rec_vid = v.vid
    WHERE   r.page_rec = '推荐'
)
,t_final AS (
    SELECT  dt
            ,crowd
            ,head_cate2
            ,rec_cate2
            ,SUM(1) AS exp
            ,SUM(share_cnt) AS share_cnt
            ,SUM(return_n_uv) AS return_n_uv
            ,SUM(new_exposure_cnt) AS new_exposure_cnt
    FROM    t_joined
    GROUP BY dt, crowd, head_cate2, rec_cate2
)
SELECT  dt
        ,crowd
        ,head_cate2
        ,rec_cate2
        ,exp
        ,share_cnt
        ,return_n_uv
        ,new_exposure_cnt
FROM    t_final
WHERE   crowd <> '其他'
AND     exp >= 1000
ORDER BY crowd, exp DESC
;
