好的,所以我在這里有點麻煩。我有user_id, subscription_id, plan, subscription_start_date, subscription_end_date。我正在尋找每個用戶購買的所有不同計劃以及相應的訂閱 ID,每個計劃只有一個 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
| 用戶身份 | 訂閱號 | 開始日期 | 結束日期 | 計劃 |
|---|---|---|---|---|
| 一種 | 123 | 2021-01-01 | 9999-01-01 | 優質的 |
| 乙 | 122 | 2021-02-03 | 9999-03-04 | 常規的 |
| 一種 | 144 | 2021-02-01 | 9999-01-01 | 優質的 |
| 一種 | 155 | 2021-03-01 | 9999-01-01 | 優質的 |
| 乙 | 167 | 2021-03-03 | 9999-03-04 | 常規的 |
| 乙 | 111 | 2020-05-18 | 2021-12-18 | 審判 |
| 乙 | 187 | 2020-06-18 | 2021-12-18 | 審判 |
期望的結果
| 用戶身份 | 訂閱號 | 開始日期 | 結束日期 | 計劃 |
|---|---|---|---|---|
| 一種 | 123 | 2021-01-01 | 9999-01-01 | 優質的 |
| 乙 | 122 | 2021-02-03 | 9999-03-04 | 常規的 |
| 乙 | 111 | 2020-05-18 | 2021-12-18 | 審判 |
非常感謝,如果您需要其他資訊,請告訴我 PS 我正在使用 Hive/Hadoop
uj5u.com熱心網友回復:
使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316053.html
