Oracle Group By 分组后取最大/小字段值

统计用户回复的信息, 要对其进行过滤, 每个手机号码只取回复的最后一条信息。

每个手机只取一条可以使用GROUP BY 进行分组, 但是怎么取最后回复的呢? 

需要使用 ORACLE 的 KEEP 函数了:

 

(SELECT MAX(MO.***CONTENT)KEEP(dense_rank LAST ORDER BY received_time) ***CONTENT,
                    MAX(MO.RECEIVED_TIME) RECEIVED_TIME,
                    MO.MOBILE_NUMBER,
                    MAX(MO.MO_ID) MO_ID,
                    MAX(mt.reply_content)KEEP(dense_rank LAST ORDER BY sent_time) rn
               FROM S*****O MO
               LEFT JOIN s****mt mt ON mo.mo_id = mt.mo_id
               WHERE mo.received_time >= to_date('2014-08-11','yyyy-mm-dd') AND mo.received_time <= to_date('2014-08-13','yyyy-mm-dd')
              GROUP BY MO.MOBILE_NUMBER)

 

 在 KEEP 内对分组的结果进行排序,dense_rank LAST ORDER BY received_time ,按照received_time排序取得最后一条, 就是最后回复的信息。 如果想取得第一条回复的信息,则用 dense_rank FIRST ORDER BY received_time。

 

 

 

你可能感兴趣的:(group by)