2016-10-10 62 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

非常感谢您的输入! –