SQL按时间戳按年月排序

时间:2019-01-31 14:48:18

标签: mysql sql sorting timestamp

我有一个带有两个时间戳(created_at,confirmed_at)的表

我想按created_at的年份和月份以及在月份内通过在以下位置进行确认对我的结果进行排序:

数据:

created_at, confirmed_at
2018-12-23, 2018-12-06
2018-12-15, 2019-01-20
2019-01-08, 2019-01-11
2019-01-12, 2019-01-13

结果:

created_at, confirmed_at
2019-01, 2019-01-13
2019-01, 2019-01-11
2018-12, 2019-01-20
2018-12, 2018-12-06

如何使用时间戳按YYYY-mm排序(以及如何使其快速->如何为该查询建立索引?)

1 个答案:

答案 0 :(得分:2)

具有year()和month()函数:

select 
  year(created_at) created_year, 
  month(created_at) created_month, 
  confirmed_at 
from t
order by created_year, created_month, confirmed_at

,或者如果只需要YYYY-MM部分:

select DATE_FORMAT(created_at, "%Y-%m"), confirmed_at from t
order by year(created_at), month(created_at), confirmed_at

或:

select DATE_FORMAT(created_at, "%Y-%m") created, confirmed_at from t
order by created, confirmed_at

或:

select DATE_FORMAT(created_at, "%Y-%m") created, confirmed_at from t
order by EXTRACT(YEAR_MONTH FROM created_at), confirmed_at