简体   繁体   中英

MySQL order by two fields, cluster fields

I've been wondering how to order rows chronologically, but also keep rows with extra flag together.

Specifically, I have table with orders

Data:

| created     | customer | ...
| 2020-01-01  | xyz      | ...
| 2020-01-10  | abc      | ...
| 2020-01-12  | xyz      | ...
| 2020-01-15  | xyz      | ...
| 2020-01-19  | abc      | ...
| 2020-01-20  | abc      | ...

Desired result:

| created     | customer | ...
| 2020-01-01  | xyz      | ...
| 2020-01-12  | xyz      | ...
| 2020-01-15  | xyz      | ...
| 2020-01-10  | abc      | ...
| 2020-01-19  | abc      | ...
| 2020-01-20  | abc      | ...

So pretty much I need "ORDER BY customers, created", but "customers" need to be ordered by their oldest order.

I hope it makes sense. And thanks in advance for your help.

select * from orders order by customer desc, created_date asc;
2020-01-01  xyz 
2020-01-12  xyz 
2020-01-15  xyz 
2020-01-10  abc 
2020-01-19  abc 
2020-01-20  abc 

You can use window functions in the order by . So:

select t.*
from t
order by min(created) over (partition by customer),
         customer,
         created;

Note that customer is included after the minimum of the creation date. This ensures that if two customers have the same creation date, their data is not all mixed together.

You can try this

select * from tablename
group by customer desc, created asc

Join a query that returns the oldest order of each customer and sort the table first by that oldest date:

select o.*
from orders o 
inner join (
  select customer, min(created) created
  from orders
  group by customer
) c on c.customer = o.customer
order by c.created, o.customer, o.created

See the demo .
Results:

| created    | customer |
| ---------- | -------- |
| 2020-01-01 | xyz      |
| 2020-01-12 | xyz      |
| 2020-01-15 | xyz      |
| 2020-01-10 | abc      |
| 2020-01-19 | abc      |
| 2020-01-20 | abc      |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM