mysql按两个字段排序,集群字段

5m1hhzi4  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(337)

我一直想知道如何按时间顺序排列行,但也要将带有额外标志的行放在一起。
具体来说,我有一张有订单的table
数据:

| 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      | ...

期望结果:

| 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      | ...

所以我非常需要“按客户创建的订单”,但是“客户”需要按他们最早的订单来订购。
我希望这有道理。谢谢你的帮助。

mrzz3bfm

mrzz3bfm1#

加入一个查询,返回每个客户最早的订单,并按最早的日期对表进行排序:

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

请看演示。
结果:

| 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      |
vof42yt1

vof42yt12#

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
oaxa6hgo

oaxa6hgo3#

可以在中使用窗口函数 order by . 所以:

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

请注意 customer 包含在最短的创建日期之后。这确保了如果两个客户具有相同的创建日期,那么他们的数据不会全部混合在一起。

iq3niunx

iq3niunx4#

你可以试试这个

select * from tablename
group by customer desc, created asc

相关问题