MySQL按两个字段排序,即群集字段

时间:2020-07-16 14:39:29

标签: mysql sql

我一直想知道如何按时间顺序对行进行排序,但是还要将带有额外标志的行保持在一起。

具体地说,我的桌子上有订单

数据:

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

几乎我需要“已创建的ORDER BY客户”,但“客户”则需要按其最早的订单进行排序。

我希望这是有道理的。在此先感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

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 

答案 1 :(得分:0)

您可以在order by中使用窗口功能。所以:

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

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

答案 2 :(得分:0)

您可以尝试

select * from tablename
group by customer desc, created asc

答案 3 :(得分:0)

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

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

请参见demo
结果:

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