如何为每个用户获取第一个订阅(假定订阅 ID 每次自动更新时都会更改)

How to get the first subscription for each user (given that subscription ids change every time it renews automatically)

好吧,我有点困惑。 我有 user_id、subscription_id、计划、subscription_start_date、subscription_end_date。 我正在寻找每个用户购买的所有不同计划以及相应的 subscription_ids,每个计划只有一个 ID(第一个)。需要注意的是,每次用户续订订阅时,订阅 ID 都会更改。因此,假设用户 A 只有一个订阅并已续订 3 次,因此有 3 个不同的订阅 ID,而用户 B 有 2 个计划并已续订两次,因此他们有 4 个订阅 ID。

我正在寻找用户 A 有 1 个 sub_id 和 1 个计划,用户 B 有 2 个子 ID 和 2 个不同的计划

这是我目前的查询

SELECT H.plan, H.user_id
FROM my_table H
INNER JOIN
    (SELECT user_id, plan, MIN(subscription_purchase_date) As first_sub_date
    FROM my_table
    GROUP BY user_id, plan) X
ON H.user_id= X.user_id AND H.subscription_purchase_date = X.first_sub

user_id subscription_id start_date end_date plan
A 123 2021-01-01 9999-01-01 Premium
B 122 2021-02-03 9999-03-04 Regular
A 144 2021-02-01 9999-01-01 Premium
A 155 2021-03-01 9999-01-01 Premium
B 167 2021-03-03 9999-03-04 Regular
B 111 2020-05-18 2021-12-18 Trial
B 187 2020-06-18 2021-12-18 Trial

期望的结果

user_id subscription_id start_date end_date plan
A 123 2021-01-01 9999-01-01 Premium
B 122 2021-02-03 9999-03-04 Regular
B 111 2020-05-18 2021-12-18 Trial

非常感谢,如果您需要更多信息,请告诉我 PS 我正在使用 Hive/Hadoop

使用 row_number() 和过滤器。

使用您的数据示例进行演示:

with my_table as (--data example, use your table instead of this CTE            
select 'A' user_id, 123 subscription_id, '2021-01-01' start_date, '9999-01-01' end_date, 'Premium' plan union all
select 'B', 122, '2021-02-03', '9999-03-04', 'Regular' union all
select 'A', 144, '2021-02-01', '9999-01-01', 'Premium' union all
select 'A', 155, '2021-03-01', '9999-01-01', 'Premium' union all
select 'B', 167, '2021-03-03', '9999-03-04', 'Regular' union all
select 'B', 111, '2020-05-18', '2021-12-18', 'Trial' union all
select 'B', 187, '2020-06-18', '2021-12-18', 'Trial'
)

select user_id, subscription_id, start_date, end_date, plan
from 
(
select user_id, subscription_id, start_date, end_date, plan,
       --Row with min start_date will be assigned rn=1
       row_number() over(partition by user_id, plan order by start_date) rn
from my_table
)s where rn=1

结果:

user_id subscription_id start_date  end_date    plan
A       123             2021-01-01  9999-01-01  Premium
B       122             2021-02-03  9999-03-04  Regular
B       111             2020-05-18  2021-12-18  Trial