2016-02-22 185 views
1

以下是一些示例數據。我試圖爲每個用戶標識獲取最近活動日期的單個記錄。如果用戶觀看在給定日期超過一部電影,記錄應根據與電影名稱相關聯的優先級來選擇sql根據多列選擇優先級

UserID MovieName ActivityDate 
1  MOV1 2015-02-12 
2  MOV2 2015-04-22 
1  MOV3 2015-03-16 
3  MOV1 2015-06-23 
2  MOV5 2016-01-01 
2  MOVH 2016-01-01 

優先與電影名關聯 -

MOV1 > MOV2 > MOV3 > MOV5 > MOVH 

預期結果:

UserID MovieName ActivityDate 
1  MOV3 2015-03-16 
2  MOV5 2016-01-01 
3  MOV1 2015-06-23 

我已經嘗試了GROUP BY和CASE的組合,但我非常確定可以有更好的方法。任何幫助表示讚賞。

回答

0

正確的答案是row_number(),但你必須要小心的order by

select m.* 
from (select m.*, 
      row_number() over (partition by UserId 
           order by ActivityDate desc, 
             (case MovieName 
               when 'MOV1' then 1 
               when 'MOV2' then 2 
               when 'MOV3' then 3 
               when 'MOV5' then 4 
               when 'MOVH' then 5 
               else 999 
              end) 
           ) as seqnum 

     from movies m 
    ) m 
where seqnum = 1; 
2
select * 
from (
select * 
, row_number() OVER (partition by id order by MovieName desc, ActivityDate desc) as rnk 
from movies) m 
where m.rnk = 1