sql题中遇到按年月进行分组的问题,记录一下。

先把日期通过date_format函数格式化,然后通过响应的年月日的表示符来取响应的值。
-- 按年分组
select 订单ID,date_format(订购日期,'%Y') as years from `订单` GROUP BY 订单ID,years

-- 按月分组(按日分组同理,取%d)
select 订单ID,date_format(订购日期,'%m') as months from `订单` GROUP BY 订单ID,months

-- 按年月
select 订单ID,date_format(订购日期,'%Y-%m') as ym from `订单` GROUP BY 订单ID,ym

网友评论