如何 return 用户每月的最大日期

How to return max date per month for user

我关注table:

而且我想 returned 每个用户每个月的最大阈值日期,所以我的最终结果应该是这样的:

我想使用分析函数 ROW_NUMBER 和 return 最大行数,但如何为每个用户每月执行一次?在 BigQuery 中有更简单的方法吗?

您可以按用户和月份对 row_number 进行分区,然后分别取第一个:

SELECT user_id, threshold_date, net_deposists_usd
FROM   (SELECT user_id, threshold_date, net_deposists_usd,
               ROW_NUMBER () OVER (PARTITION BY user_id, EXTRACT (MONTH FROM threshold_date)
                                   ORDER BY net_deposists_usd DESC) AS rk
        FROM   mytable)
WHERE  rk = 1

BigQuery 现在支持 qualify,它可以满足您的所有需求。对于月份,只需使用 date_trunc():

select t.*
from t
qualify row_number() over (partition by user_id, date_trunc(threshold_date, month) 
                           order by threshold_date desc, net_deposits_usd desc
                          );

一个简单的替代方案使用数组和 group by:

select array_agg(t order by threshold_date desc, net_deposits_usd desc limit 1)[ordinal(1)].*
from t
group by user_id, date_trunc(threshold_date, month) ;