通过GROUP,HAVING,recency等查询SQL

时间:2017-05-26 06:13:35

标签: sql postgresql

我的' call_logs' table包含字段:id,phone_number,call_dialed_time,is_success。 (如果对phone_number的调用失败,那么我们输入记录并稍后再次尝试调用)

对于尚未成功拨打的每个phone_number,我想获取最近一次失败的phone_number和call_dialed_time。

如何查询?

2 个答案:

答案 0 :(得分:1)

试试这个

 select t1.* from call_logs as t1 inner  join 
 (
 select 
 phone_number, max(call_dialed_time) as call_dialed_time from call_logs
 where is_success=0
 group by phone_number
 ) as t2 on t1.phone_number=t2.phone_number and t1.call_dialed_time=t2.call_dialed_time

答案 1 :(得分:0)

试试这个。

select distinct phone_number ,call_dialed_time from call_logs where phone_number not  in(
select phone_number from call_logs group by phone_number having count(is_success) >0
)  order by call_dialed_time