在移动运营商的业务中,客户都有各自的手机号码,我们可以把客户的手机号码可以根据其末位数字的奇偶性进行分类。通过分析奇数号码客户和偶数号码客户每天的消费情况,可以了解不同类型客户的消费习惯和趋势,有助于运营商制定更有针对性的营销策略和优化服务。
现在有一个业务场景,要求计算每天奇数号码客户和偶数号码客户的消费金额总和。如果某天没有奇数或偶数号码客户的消费,显示为 0,返回结果表以消费日期升序排序。 本次以梧桐数据库为例进行SQL
实现及思路讲解。
梧桐数据库消费记录表建表语句
create table consume_record (
consume_id integer, -- 客户id
phone_number varchar(32), -- 手机号码
amount integer , -- 消费金额
consume_date date, -- 消费日期
primary key (consume_id)
);
通过insert
语句向梧桐数据库插入样例数据
insert into consume_record values(1, '13800138000', 100, '2023-01-01');
insert into consume_record values(2, '13800138001', 150, '2023-01-01');
insert into consume_record values(3, '13800138002', 200, '2023-01-01');
insert into consume_record values(4, '13800138003', 250, '2023-01-01');
insert into consume_record values(5, '13800138004', 300, '2023-01-01');
insert into consume_record values(6, '13800138005', 350, '2023-01-01');
insert into consume_record values(7, '13800138006', 400, '2023-01-02');
insert into consume_record values(8, '13800138007', 450, '2023-01-02');
insert into consume_record values(9, '13800138008', 500, '2023-01-02');
insert into consume_record values(10, '13800138009', 550, '2023-01-02');
insert into consume_record values(11, '13800138010', 600, '2023-01-02');
insert into consume_record values(12, '13800138011', 650, '2023-01-02');
insert into consume_record values(13, '13800138012', 700, '2023-01-03');
sql
实现思路分解1、提取手机号码的末位数字
2、判断手机号码的末位数字的奇偶性
3、根据奇偶型计算消费总额
4、按消费日期升序排列,显示了每天奇数号码客户和偶数号码客户的消费总额。如果某天没有奇数或偶数号码客户的消费,显示为 0。
sql
代码实现select
consume_date, -- 消费日期
-- 提取手机号码的最后一个字符
-- 通过mod函数判断奇偶性,余数为 0,则表示偶数;余数为 1,则表示奇数
sum(case when mod(substr(phone_number, -1) , 2) = 0 then amount else 0 end) as even_amount, -- 计算末位数字为偶数的客户的消费总额
sum(case when mod(substr(phone_number, -1) , 2) = 1 then amount else 0 end) as odd_amount -- 计算末位数字为奇数的客户的消费总额
from
consume_record -- 从消费记录表中读取数据
group by
consume_date -- 按照消费日期分组
order by
consume_date asc; -- 按照消费日期升序排列
sql
实现结果consume_date | even_amount | odd_amount |
---|---|---|
2023-01-01 | 600 | 750 |
2023-01-02 | 1500 | 1650 |
2023-01-03 | 700 | 0 |
author:chenhui