簡體   English   中英

presto sql 查找具有按順序插入的特定列值的 id

[英]presto sql to find ids having specific column values inserted in sequence

我有一張桌子

user_id  user_type   date_updated

1         Beginner   10/10/2020
1         Moderate   10/11/2020
1         Advanced   10/12/2020
2         Beginner   10/10/2020
2         Moderate   10/11/2020
2         Expert     10/12/2020
2         Advanced   10/13/2020

我正在尋找sql 來查找 user_idsuser_type (Beginner->Moderate->Advanced) 按順序遞增的方式由 date_updated 排序。

上表的結果應該是 user_id 1,因為它有初學者(10/10/2020)-> 中等(10/11/2020)-> 高級(10/12/2020)

user_id 2 不合格,因為所有必需的類型都沒有相互跟隨初學者->中等->專家->高級

一種方法是在having條件的邏輯聚合:

select user_id
from t
group by user_id
having max(case when user_type = 'Beginner' then date_updated end) < max(case when user_type = 'Moderate' then date_updated end) and
       max(case when user_type = 'Moderate' then date_updated end) < max(case when user_type = 'Advanced' then date_updated end);

編輯:

根據修改后的問題,使用lag() 假設給定用戶沒有重復的用戶類型:

select user_id
from (select t.*,
             lag(user_type) over (partition by user_id order by date_updated) as prev_user_type,
             lag(user_type, 2) over (partition by user_id order by date_updated) as prev2_user_type
      from t
     ) t
where prev2_user_type = 'Beginner' and
      prev_user_type = 'Moderate' and
      user_type = 'Advanced'
  
   

一種方法使用聚合:

select user_id
from mytable
group by user_id
having array_agg(user_type order by date_updated) = array['Beginner', 'Moderate', 'Advanced']

暫無
暫無

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

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