[英]First Unique Sql row
I have a MySql table of users order and it has columns such as:我有一个用户订单的 MySql 表,它有如下列:
user_id | timestamp | is_order_Parent | Status | 1 | 10-02-2020 | N | C | 2 | 11-02-2010 | Y | D | 3 | 11-02-2020 | N | C | 1 | 12-02-2010 | N | C | 1 | 15-02-2020 | N | C | 2 | 15-02-2010 | N | C |
I want to count number of new custmer per day defined as: a customer who orders non-parent order and his order status is C AND WHEN COUNTING A USER ONCE IN A DAY WE DONT COUNT HIM FOR OTHER DAYS我想计算每天新客户的数量,定义为:订购非父订单且其订单状态为 C 的客户,并且在一天计算一次用户时,我们不会为其他天计算他
An ideal resulted table will be:理想的结果表将是:
Timestamp: Day | Distinct values of User ID 10-02-2020 | 1 11-02-2010 | 1 12-02-2010 | 0 <--- already counted user_id = 1 above, so no need to count it here 15-02-2010 | 1
table name is cscart_orders表名是 cscart_orders
If you are running MySQL 8.0, you can do this with window functions an aggregation:如果您正在运行 MySQL 8.0,您可以使用窗口函数和聚合来执行此操作:
select timestamp, sum(timestamp = timestamp0) new_users
from (
select
t.*,
min(case when is_order_parent = 'N' and status = 'C' then timestamp end) over(partition by user_id) timestamp0
from mytable t
) t
group by timestamp
The window min()
computes the timestamp when each user became a "new user".窗口
min()
计算每个用户成为“新用户”时的时间戳。 Then, the outer query aggregates by date, and counts how many new users were found on that date.然后,外部查询按日期聚合,并计算在该日期找到的新用户数。
A nice thing about this approach is that it does not require enumerating the dates separately.这种方法的一个好处是它不需要单独枚举日期。
You can use two levels of aggregation:您可以使用两个级别的聚合:
select first_timestamp, count(*)
from (select t.user_id, min(timestamp) as first_timestamp
from t
where is_order_parent = 'N' and status = 'C'
group by t.user_id
) t
group by first_timestamp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.