2016-10-10 64 views
1

我的表是獲取在表中是唯一的值:由多個條件

表1

ID  Payment_type  Time 
A   X   2014 01 
A   Y   2014 08 
B   X   2013 10 
A   Y   2014 08 
B   Z   2013 09 
A   Y   2012 01 
A   Z   2014 08 

和結果應該是

ID  Payment_type  
A   Y   
B   X  

的要求是在最大時間爲第一次看ID。如果只有1個觀察值,則獲取付款類型的相應值。如果某個ID的最長時間超過1行,請獲得最多發生的付款類型(如果是平局,則選擇任意值)。

+1

請用您正在使用的數據庫標記您的問題。 –

+0

同時告訴「時間」列的數據類型是什麼? –

+0

數據類型的時間是'bigint' –

回答

2

爲了解決這個問題,你需要在每個值的頻率在每個時間:

select id, payment_type, time, count(*) as cnt 
from t 
group by id, payment_type, time; 

接下來,您需要選擇基於時間每個id然後cnt最大值。最簡單的方法使用:row_number()

select id, payment_type, time 
from (select id, payment_type, time, count(*) as cnt, 
      row_number() over (partition by id order by time desc, cnt desc) as seqnum 
     from t 
     group by id, payment_type, time 
    ) ipt 
where seqnum = 1; 
+0

非常感謝您的輸入! –