SQL代码详解:按地区和产品类型统计用户数和总费用
SQL代码详解:按地区和产品类型统计用户数和总费用
本文将详细分析以下SQL代码的功能和实现逻辑:sqlinsert overwrite table temp_yt_gwbyl_result partition (month_id = '${v_month}')select '全国' prov_part, pro_type, count(distinct cbss_user_id) user_num, sum(total_fee) total_feefrom temp_yt_gwbyl_userwhere month_id = '${v_month}'group by pro_type, '全国'union allselect b.prov_part, a.pro_type, count(distinct cbss_user_id) user_num, sum(total_fee) total_feefrom ( select prov_id, pro_type, cbss_user_id, total_fee from temp_yt_gwbyl_user where month_id = '${v_month}' ) a left join ( select prov_id, prov_desc, case when ord_id3 <= 10 then '北10' when ord_id3 > 10 then '南21' end prov_part from DIM_PROV_ORD ) b on a.prov_id = b.prov_idgroup by a.pro_type, b.prov_partunion allselect b.prov_desc prov_part, a.pro_type, count(distinct cbss_user_id) user_num , sum(total_fee) total_feefrom temp_yt_gwbyl_user a left join ( select prov_id, prov_desc from DIM_PROV_ORD ) b on a.prov_id = b.prov_idwhere month_id = '${v_month}'group by a.pro_type, b.prov_desc;
这段代码的功能是:统计指定月份(${v_month})不同地区和产品类型的用户数量和总费用,并将结果插入到名为 temp_yt_gwbyl_result 的分区表中。
代码解析:
- 插入数据: -
insert overwrite table temp_yt_gwbyl_result partition (month_id = '${v_month}'): 将查询结果插入到表temp_yt_gwbyl_result中,并根据month_id进行分区。2. 数据查询: - 代码使用了union all将三个查询结果合并在一起。 - 第一个查询: - 统计全国范围内,不同产品类型('pro_type')的用户数量('user_num')和总费用('total_fee')。 - 第二个查询: - 使用子查询和左连接,将temp_yt_gwbyl_user表和DIM_PROV_ORD表关联起来。 - 根据DIM_PROV_ORD表中的ord_id3字段,将地区分为 '北10' 和 '南21' 两个区域。 - 统计每个区域内,不同产品类型的用户数量和总费用。 - 第三个查询: - 使用左连接,将temp_yt_gwbyl_user表和DIM_PROV_ORD表关联起来。 - 统计每个省份('prov_desc')内,不同产品类型的用户数量和总费用。3. 数据聚合: - 每个查询都使用了group by子句,根据 'pro_type' 和地区字段进行分组聚合。 - 使用count(distinct cbss_user_id)计算不同用户的数量,使用sum(total_fee)计算总费用。
总结:
这段SQL代码通过多个查询和联合操作,实现了按地区和产品类型统计用户数量和总费用的功能。其中,union all、子查询、左连接和分组聚合等操作的运用,使得代码逻辑清晰,易于理解。
原文地址: https://www.cveoy.top/t/topic/fBhj 著作权归作者所有。请勿转载和采集!