簡體   English   中英

獲取指定日期之前的項目的運行唯一計數,類似於運行總數,但不是運行的唯一計數

[英]Get the running unique count of items till a give date, similar to running total but instead a running unique count

我有一張包含用戶購物數據的表格,如下所示

在此處輸入圖像描述

我想要一個類似於運行總計的 output,但我想要用戶按日期購買的唯一類別計數的運行總計。

在此處輸入圖像描述

我知道我必須在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

所需 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

考慮以下方法

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               

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM