SQL 滚动查询新买家的语句

SQL statement to query new buyers on rolling basis

我目前有一个订单 table 看起来像这样:

purchase_date | item_id | item_name | user_id
2/3/2020      | 123     | abc       | 987
3/3/2020      | 123     | abc       | 987
3/3/2020      | 123     | abc       | 876
3/3/2020      | 234     | bcd       | 987
...

我一直在尝试创建一个 SQL 语句,该语句将 return 像这样通过计数(不同的 user_id) :

purchase_date | item_id | item_name | number of buyers new to item
2/3/2020      | 123     | abc       | 1 
3/3/2020      | 123     | abc       | 1
3/3/2020      | 234     | bcd       | 1

当然会有多个item_ids顺序table.

我想要实现的是获得每天之前从未购买过该特定商品的买家的滚动数量。

例如,以上述订单table为例,有1个买家1个2/3/2020,2个买家1个3/3/2020。但是,User_id987在2/3/2020买了同样的东西,所以我不想统计这个用户,所以3/3/2020的最终结果应该只有1个用户。

User_id 987 仍将计为 item_id 234,因为此用户之前未在订单 table.

中购买过此商品

订单中的商品 table 将在每个星期一刷新,因此我正在尝试构建一个查询,该查询将每天 return 向我显示每个特定商品的新买家数量(即之前没有买过),从周一到周日。

这是使用 CROSS JOIN 的概念,还是以某种方式临时 tables,或者这是一个比我预期的更复杂的想法,在 SQL 中执行它查询格式?

谢谢!

使用两级聚合:

select first_pd, item_id, item_name, count(*) as num_first_purchases
from (select user_id, item_id, item_name, min(purchase_date) as first_pd
      from t
      group by user_id, item_id, item_name
     ) ui
group by first_pd, item_id, item_name
order by first_pd, item_id, item_name;