Question

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  <-  |
===========================================================
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top