SQL代码详解:用户费用统计脚本
SQL代码详解:用户费用统计脚本
本篇文章将详细分析一段用于统计用户费用信息的SQL代码,该代码实现了将数据插入到分区表,并根据不同渠道类型进行用户数量和费用的统计。
-- 执行脚本--p_acct_user_fee
insert overwrite table temp_yt_sxsj partition (month_id = '${v_month}')
select a.prov_id,
a.chnl_type,
a.user_num,
a.total_fee
from (
select a.prov_id,
case
when level1_id = 'P03' then '基础数据产品线(全渠道)'
when level2_id = 'P0401' then '互联网专线产品系列(全渠道)'
else '其他'
end chnl_type,
count(distinct a.user_id) user_num,
sum(b.total_fee) total_fee
from (
select prov_id,
cbss_user_id user_id,
level1_id,
level2_id
from temp_yt_gw_user
where month_id='${v_month}'
group by prov_id, cbss_user_id, level1_id, level2_id
) a
left join
(
select user_id,
prov_id,
sum(total_fee) total_fee
from dwa.dwa_v_m_cus_cb_sing_charge --linjh 由db_der.DWA_V_M_CUS_CB_CHARGE修改为dwa.dwa_v_m_cus_cb_sing_charge
where month_id = '${v_month}'
and substr(device_number,1,4)!='1454' and substr(device_number,1,4)!='1457' --linjh 新增的查询条件
group by user_id, prov_id
) b
on a.prov_id = b.prov_id and a.user_id = b.user_id
group by a.prov_id,
case
when level1_id = 'P03' then '基础数据产品线(全渠道)'
when level2_id = 'P0401' then '互联网专线产品系列(全渠道)'
else '其他'
end
union all
-- 省略中间部分代码,逻辑与第一部分类似,只是渠道类型判断条件不同
) a
where a.chnl_type <> '其他'
group by a.prov_id, a.chnl_type, a.user_num, a.total_fee
order by a.prov_id, a.chnl_type;
代码功能:
这段代码的主要功能是统计不同渠道的用户数量和总费用,并将结果插入到名为 temp_yt_sxsj 的分区表中,具体步骤如下:
- 数据准备: 从
temp_yt_gw_user表中提取用户的基本信息,包括省份ID (prov_id), 用户ID (user_id), 产品线ID (level1_id, level2_id) 等。 - 费用信息关联: 通过左连接
dwa.dwa_v_m_cus_cb_sing_charge表,根据用户ID和省份ID匹配用户的费用信息,并计算总费用 (total_fee)。 - 渠道类型划分: 根据产品线ID或其他条件,使用
case when语句将用户划分为不同的渠道类型,例如 '基础数据产品线(全渠道)', '互联网专线产品系列(政企渠道)' 等。 - 分组统计: 按照省份ID和渠道类型对用户进行分组,并使用
count(distinct user_id)计算每个分组的用户数量 (user_num), 使用sum(total_fee)计算每个分组的总费用。 - 结果过滤: 使用
where条件过滤掉渠道类型为 '其他' 的记录。 - 数据插入: 将最终的统计结果插入到
temp_yt_sxsj表的指定分区 (month_id = '${v_month}') 中,并按照省份ID和渠道类型排序。
代码特点:
- 使用了分区表,可以提高查询效率。
- 使用了左连接,确保即使在费用表中没有匹配记录的情况下,用户基本信息也能被统计。
- 使用了
case when语句,实现了灵活的渠道类型划分逻辑。 - 使用了
union all操作符,将不同渠道类型的统计结果合并在一起。
总结:
这段SQL代码结构清晰,逻辑严谨,实现了一个典型的用户费用统计功能。通过学习这段代码,可以加深对SQL中数据准备、关联、分组统计、结果过滤等操作的理解,并学习如何使用 case when 语句和 union all 操作符处理复杂的数据逻辑。
原文地址: https://www.cveoy.top/t/topic/fBcu 著作权归作者所有。请勿转载和采集!