如何计算特定日期第一次出现唯一 ID 的次数?

How to get a count of the times the first occurrence of an unique ID is on a specific day?

所以我有两个表:

customer_dimension:

sk_customer | first_name | last_name | acq_channel | acq_date |  customer_id
-----------------------------------------------------------------------------
411           Alex          Hum       Offline        2019-03-02  44586344
422           Eric          Spong     Offline        2019-02-02  44323233
447           Eddie         Peng      TV             2019-05-07  44782233

boxes_shipped:

box_id | fk_box_sku | fk_customer | fk_geography | week |  delivery_date
----------------------------------------------------------------------------
123      321          447           Syd            2       2019-04-02      
124      322          422           WA             3       2019-02-05
125      323          411           WA             4       2019-05-07

fk_customer 通过外键约束引用 sk_customer。

我想找到一种方法来计算 fk_customer 在星期二第一次出现的次数,即在星期二收到第一个盒子的人数。因此,如果客户在星期二订购了第二盒,则不会增加数量。

我该如何编写查询以查看交货日期是否为星期二?然后只计算第一次出现的 fk_customer?

参考您的要求,

  • 要计算每个日期的 fk_customer 订单,您可以使用 group by delivery_date, fk_customer 并在其上使用 count(*) 聚合器。

  • 要从日期中获取特定的日期名称,您可以搜索特定于您的 DBMS 的库函数。

您所需查询的 MySQL 实现将是:

select count(*) repeatedOrders, fk_customer, delivery_date from boxes_shipped group by delivery_date, fk_customer where dayname(delivery_date) = 'Tuesday'.

我会推荐两个聚合级别:

select count(*)
from (select fk_customer, min(delivery_date) as first_delivery_date
      from boxes_shipped
      group by fk_customer
     ) c
where dayname(first_delivery_date) = 'Tuesday';

如果有人想知道,我用过:

with order_values as(
     select *, rank() over(partition by delivery_date,fk_customer)
as order_value_rank
from boxes_shipped
where DATE_FORMAT(delivery_date, '%a') = 'Tues'
)

select count(*) as 'Number of people that received their 1st box on Tues'
from order_values
where order_value_rank =1;