Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL按两个字段排序,群集字段_Mysql_Sql - Fatal编程技术网

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

MySQL按两个字段排序,群集字段,mysql,sql,Mysql,Sql,我一直想知道如何按时间顺序对行进行排序,但也要将带有额外标志的行放在一起 具体来说,我有一张有订单的桌子 数据: 预期结果: | created | customer | ... | 2020-01-01 | xyz | ... | 2020-01-12 | xyz | ... | 2020-01-15 | xyz | ... | 2020-01-10 | abc | ... | 2020-01-19 | 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      | ...

所以我几乎需要“按客户创建订单”,但“客户”需要按他们最早的订单进行订购


我希望这是有道理的。提前感谢您的帮助。

您可以按的顺序使用窗口功能。因此:

select t.*
from t
order by min(created) over (partition by customer),
         customer,
         created;
请注意,
customer
包含在最短创建日期之后。这确保了如果两个客户具有相同的创建日期,他们的数据不会全部混合在一起。

您可以尝试此方法

select * from tablename
group by customer desc, created asc

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

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
请参阅。
结果:


不。。。它是按客户价值排序的,而不是按订购时间排序的。请在回答中添加一些解释,以便其他人可以从中学习
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      |
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