SQL:运行不同值的总计数
我试图在一个窗口中获得唯一值的滚动数 我的桌子是这样的:SQL:运行不同值的总计数,sql,google-bigquery,aggregate-functions,cumulative-sum,Sql,Google Bigquery,Aggregate Functions,Cumulative Sum,我试图在一个窗口中获得唯一值的滚动数 我的桌子是这样的: SELECT user_id , order_date , product FROM example_table WHERE user_id = 1 ORDER BY order_date ASC 用户id 订单日期 产品 1. 2021-01-01 A. 1. 2021-01-01 B 1. 2021-01-04 A. 1. 2021-01-07 C 1. 2021-01-09 C 1. 2021-01-20
SELECT
user_id
, order_date
, product
FROM example_table
WHERE user_id = 1
ORDER BY order_date ASC
用户id
订单日期
产品
1.
2021-01-01
A.
1.
2021-01-01
B
1.
2021-01-04
A.
1.
2021-01-07
C
1.
2021-01-09
C
1.
2021-01-20
A.
对于每个项目,您可以记录它出现的最早日期。然后把这些加起来:
select et.* except (seqnum),
countif(seqnum = 1) over (partition by user_id order by order_date) as running_distinct_count
from (select et.*,
row_number() over (partition by user_id, product order by order_date) as seqnum
from example_table et
) et
下面是BigQuery的示例
select * except(cum_products),
(select count(distinct product) from t.cum_products product) as cum_dist_count
from (
select *,
array_agg(product) over prev_rows as cum_products
from example_table
window prev_rows as (partition by user_id order by order_date)
) t
如果应用于您问题中的样本数据
with example_table as (
select 1 user_id, '2021-01-01' order_date, 'A' product union all
select 1, '2021-01-02', 'B' union all
select 1, '2021-01-04', 'A' union all
select 1, '2021-01-07', 'C' union all
select 1, '2021-01-09', 'C' union all
select 1, '2021-01-20', 'A'
)
输出为
这正是我想要的-谢谢@格里泽克。如果这回答了你的问题,你可以接受答案。你有机会尝试吗?