Get records with most recent timestamp and also with proper grouping

StackOverflow https://stackoverflow.com/questions/22158355

  •  19-10-2022
  •  | 
  •  

سؤال

Here is an order table with id, order time and buyer's phone number

I am trying to wrap up an Oracle query to filter out the latest phone order per each phone number:

So this may request MAX(order_time) but also need group by phone number.

Following is the table structure and data for example, but the actual order table get about 20 fields so GROUP BY clause may very long so made the query very clumsy

So what could be the best solution with best performance?

Thanks

===========================================================
|   order id  |       order_time        |      phone      |
===========================================================
|     228     | 12-23-2013 12:25:28 PM  | 1234567890      |
===========================================================
|     236     | 11-16-2013 11:46:24 AM  | 6665558887  <-  |
===========================================================
|     249     | 02-21-2014 10:25:16 PM  | 1234567890  <-  |
===========================================================
|     256     | 01-14-2014 10:25:33 PM  | 4567891230      |
===========================================================
|     269     | 02-21-2013 11:49:57 AM  | 1234567890      |
===========================================================
|     288     | 02-25-2014 01:25:05 PM  | 4567891230  <-  |
===========================================================
|     ...     | ......................  | ..........      |
===========================================================
|     299     | 12-23-2013 12:25:28 PM  | 2223336669  <-  |
===========================================================

This is the expected query result:

===========================================================
|   order id  |       order_time        |      phone      |
===========================================================
|     236     | 11-16-2013 11:46:24 AM  | 6665558887  <-  |
===========================================================
|     249     | 02-21-2014 10:25:16 AM  | 1234567890  <-  |
===========================================================
|     288     | 02-25-2014 01:25:05 PM  | 4567891230  <-  |
===========================================================
|     ...     | ......................  | ..........      |
===========================================================
|     299     | 12-23-2013 12:25:28 PM  | 2223336669  <-  |
===========================================================
هل كانت مفيدة؟

المحلول

You need a Windowed Aggregate Function:

select * 
from
 (
   select tab.*, 
      rank() over (partition by phone order by order_time desc) rnk
 ) dt
where rnk = 1
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top