[英]Get the running unique count of items till a give date, similar to running total but instead a running unique count
I have a table with user shopping data as shown below我有一张包含用户购物数据的表格,如下所示
I want an output similar to running total but instead I want the running total of the count of unique categories that the user has shopped for by date.我想要一个类似于运行总计的 output,但我想要用户按日期购买的唯一类别计数的运行总计。
I know I have to make use of ROWS PRECEDING AND FOLLOWING
in the count
function but I am not able to user count(distinct category)
in a window function我知道我必须在count
function 中使用ROWS PRECEDING AND FOLLOWING
但我无法在 window function 中使用用户count(distinct category)
Dt category userId
4/10/2022 Grocery 123
4/11/2022 Grocery 123
4/12/2022 MISC 123
4/13/2022 SERVICES 123
4/14/2022 RETAIl 123
4/15/2022 TRANSP 123
4/20/2022 GROCERY 123
Desired output所需 output
Dt userID number of unique categories
4/10/2022 123 1
4/11/2022 123 1
4/12/2022 123 2
4/13/2022 123 3
4/14/2022 123 4
4/15/2022 123 5
4/20/2022 123 5
Consider below approach考虑以下方法
select Dt, userId,
( select count(distinct category)
from t.categories as category
) number_of_unique_categories
from (
select *, array_agg(lower(category)) over(partition by userId order by Dt) categories
from your_table
) t
if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.