mysql - 对表格进行排序

标签 mysql sql database

我想使用sql对下表XYZ进行排序,
这里的Id是主键。

----------------------------------------
Id | Date        |Product   | Time 
----------------------------------------
1  | 01-02-2016  |C         |10:00
2  | 01-02-2016  |B         |10:30
3  | 01-02-2016  |A         |11:00
4  | 01-02-2016  |C         |11:30
5  | 01-02-2016  |B         |12:00
6  | 01-02-2016  |A         |12:30
7  | 01-02-2016  |C         |13:00
8  | 01-02-2016  |B         |13:30
9  | 02-02-2016  |D         |07:00
10 | 02-02-2016  |C         |07:30
11 | 02-02-2016  |E         |08:00
12 | 02-02-2016  |D         |08:30
13 | 02-02-2016  |E         |09:00
14 | 02-02-2016  |A         |09:30

我需要以这样的方式对其进行排序,以找到每天最短时间的产品并按时间排序,然后找到下一个最早时间的产品并按以下方式排序。
< br/>

Id  |Date      |Product |Time 
1   |01-02-2016|    C   |10:00
4   |01-02-2016|    C   |11:30
7   |01-02-2016|    C   |13:00
2   |01-02-2016|    B   |10:30
5   |01-02-2016|    B   |12:00
8   |01-02-2016|    B   |13:30
3   |01-02-2016|    A   |11:00
6   |01-02-2016|    A   |12:30
9   |02-02-2016|    D   |07:00
12  |02-02-2016|    D   |08:30
10  |02-02-2016|    C   |07:30
11  |02-02-2016|    E   |08:00
13  |02-02-2016|    E   |09:00
14  |02-02-2016|    A   |09:30

最佳答案

select t1.*
from XYZ t1
join (
  select Date, Product, min(Time) as minTime
  from XYZ 
  group by Date, Product
) t2 using(Date, Product)
order by str_to_date(t1.Date, '%d-%m-%Y'), t2.minTime, t1.Time

http://sqlfiddle.com/#!9/00209f/3

关于mysql - 对表格进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528082/

相关文章:

php - 更好的查询添加或实现标签或标记

sql - 尽管已对有序列建立了索引,但为什么我的 SQL Server ORDER BY 仍然很慢?

mysql - 类似 Facebook 的邮箱 View ,在 GROUP BY 之前使用 ORDER BY

sql - 可扩展数据库标记模式

SQL 服务器 : update primary key after different insert statement

php - Laravel Eloquent 查询顺序按时间字段的 DESC 和 AM/PM

mysql - 导入 CSV 换行问题

php - 关闭连接 PDO

mysql - 仅当所有行具有相同值时如何从 Select 语句输出

database - 将 Web 服务中的数据缓存到数据库中是个好主意吗?