在给定日期之前获取项目的运行唯一计数,类似于运行总计,而是运行唯一计数

拉吉

我有一个包含用户购物数据的表格,如下所示

在此处输入图像描述

我想要一个类似于运行总数的输出,但我想要用户按日期购买的唯一类别计数的运行总数。

在此处输入图像描述

我知道我必须ROWS PRECEDING AND FOLLOWINGcount函数中使用,但我无法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

期望的输出

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
米哈伊尔·伯利安特

考虑以下方法

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               

如果应用于您问题中的样本数据 - 输出是

在此处输入图像描述

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章