目录
一:背景
二:实现过程
一:背景
最近需要开发一个数据统计的功能,主要是按照各种维度统计客户的数据,一般是按照日期来展示数量和变化情况。下面我们来梳理下实现的过程。
二:实现过程
1:梳理涉及统计的表
首先我们梳理涉及的统计表。我们可以根据需求来梳理,假定需求是以登录员工为例统计该员工下的客户信息,假如功能是员工持有的客户数量,员工持有的下单客户数量,员工持有的认证客户数量,员工持有的客户下单总金额等,这里涉及客户表和订单表
2:确定统计计算方法
我们已经确定涉及的表是客户表和订单表,要计算登录员工的客户信息和下单信息。可以确定我们需要输出持有客户数量,下单客户数量,认证客户数量,下单客户总金额
我们按照每个数量逐一计算:
客户数量:
select count(*) as total_num from customer where user_id=1
这里的客户数量,也可以根据员工名字或者时间进行搜索
select count(*) as total_num from customer where user_id=1 or user_name = '小' and create_time between '2024-05-06' and '2024-06-06'
下单客户数量:
select count(*) as order_num from customer where user_id=1 and customer_id in (select distinct user_id from order);
认证客户数量:
select count(*) as total_num from customer where user_id=1 and status = 1;
下单客户总金额:
select sum(order_amount) as amount from sorder where user_id in (select customer_id from customer where user_id=1 )
上面我们已经实现了每个数量的统计,那么如何合并四个数量到一个sql中呢,可以使用union all
SELECT
sum(a.total_num) AS total_num,
sum(a.order_num) AS order_num,
sum(a.auth_num) AS auth_num,
sum(a.amount) AS amount
FROM
(
SELECT
count(*) as total_num,
0 as order_num,
0 AS auth_num,
0 AS amount
FROM
shrimp_crm_customer_new
WHERE
owner_user_id = 1 UNION ALL
SELECT
0 AS total_num,
count(*) as order_num,
0 AS auth_num,
0 AS amount
FROM
shrimp_crm_customer_new
WHERE
owner_user_id = 1
AND customer_id IN ( SELECT DISTINCT uid FROM shrimp_shop_order )
UNION ALL
SELECT
0 AS total_num,
0 AS order_num,
count(*) AS auth_num,
0 AS amount
FROM
shrimp_crm_customer_new
WHERE
owner_user_id = 1
AND STATUS = 1 UNION ALL
SELECT
0 AS total_num,
0 AS order_num,
0 AS auth_num,
sum(order_amount ) AS amount
FROM
shrimp_shop_order
WHERE
uid IN ( SELECT customer_id FROM shrimp_crm_customer_new WHERE owner_user_id = 1 )
) a
这里我们合并四个值为一条记录,方便返回接口值
后续如果需要增加筛选,需要在每个子sql里增加条件。