我正在尝试获取订单总量,以及 30 天内的唯一客户数量。
我有这张桌子:
order_id、order_date、order_country、customer_id。
(1, '2021/03/04', 'SWE', 1),
(2, '2021/03/01', 'SWE', 1),
(3, '2021/03/01', 'DK', 3),
(4, '2021/03/01', 'DK', 3),
(5, '2021/03/03', 'NOR', 2),
(6, '2021/02/27', 'DK', 3),
(7, '2020/12/30', 'Ger', 4);
我尝试过这样的事情:
SELECT order_date
, COUNT(order_id) as orderAmount
, COUNT(distinct customer_id) as customerAmount
FROM orders
WHERE order_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP
BY order_date
这将获得每个日期的订单总数,这正是我想要的。但它只计算每个日期而不是每月的唯一客户,因此同一客户出现多次。我已经尝试了这个 sql 脚本的小变化,但不能让它工作。
答案 0 :(得分:0)
请检查这是否是您想要的答案。
架构(MySQL v5.5)
create table orders (order_id int, order_date date, order_country varchar(10), customer_id int);
insert into orders values(1, '2021/03/04', 'SWE', 1);
insert into orders values(2, '2021/03/01', 'SWE', 1);
insert into orders values(3, '2021/03/01', 'DK', 3);
insert into orders values(4, '2021/03/01', 'DK', 3);
insert into orders values(5, '2021/03/03', 'NOR', 2);
insert into orders values(6, '2021/02/27', 'DK', 3);
insert into orders values(7, '2020/12/30', 'Ger', 4);
查询 #1
SELECT
o.order_date,COUNT(order_id) as orderAmount
, coalesce(max(Customer_Count),0) as customerAmount
FROM orders o left join (select order_date,count(distinct customer_id)Customer_Count from orders o where
not exists (select customer_id from orders oa where o.customer_id=oa.customer_id and oa.order_date<o.order_date
and oa.order_date > now() - INTERVAL 30 DAY )
group by order_date) oc on o.order_date=oc.order_date
WHERE o.order_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
group by o.order_date
order by o.order_date;
订单日期 | 订单金额 | 客户金额 |
---|---|---|
2021-02-27 | 1 | 1 |
2021-03-01 | 3 | 1 |
2021-03-03 | 1 | 1 |
2021-03-04 | 1 | 0 |
答案 1 :(得分:0)
只计算客户第一次出现的时间:
SELECT order_date, COUNT(*) as num_orders,
COUNT(DISTINCT customer_id) as distinct_customers_on_day,
SUM(SUM(seqnum = 1)) OVER (ORDER BY order_date) as running_distinct_customers
FROM (SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) as seqnum
FROM orders o
WHERE o.order_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
) o
GROUP BY order_date;
Here 是一个 db<>fiddle。