mysql显示12个月,MySQL最近12个月中按月记录的总数

Hello I'm using this sql query to get the last 12 month records based on month for chart representation:

SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,

DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,

drives.departure,

drives.destination,

drives.route,

CONCAT(drivers.name, " ", drivers.surname) as driver,

drivers.id as driver_id

FROM drives, drivers WHERE drives.driver = drivers.id

AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH) ORDER BY drives.timestamp Asc

however if there are no records for a month it is not included in the result set as expected, and I'm doing a lot of calculations with php to accomplish what I want.

My question is this: Is there a way to retrieve a simple result set with the sum of drives of each month for the last 12 months AND if there are 0 drives for a month it must be also included-shown in the result set.

解决方案

You need to do an outer join with a table that contains a row for each month. Assuming you don't have such a table, you can create it on the fly with a hard-coded UNION query:

SELECT * FROM

(SELECT DATE_FORMAT(now(), "%b") as Month

UNION

SELECT DATE_FORMAT(now() - INTERVAL 1 MONTH), "%b")

UNION

SELECT DATE_FORMAT(now() - INTERVAL 2 MONTH), "%b")

UNION

...

SELECT DATE_FORMAT(now() - INTERVAL 11 MONTH), "%b")) AS Months

LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,

drives.timestamp,

DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,

drives.departure,

drives.destination,

drives.route,

CONCAT(drivers.name, " ", drivers.surname) as driver,

drivers.id as driver_id

FROM drives, drivers WHERE drives.driver = drivers.id

AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data

ON Months.Month = data.Month

ORDER BY data.timestamp

Any months with no records will have one row with NULL in the data columns.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值