MySQL之统计查询,按月查询每天数据,无数据自动填充0
程序员文章站
2024-03-25 10:58:10
...
MySQL之统计查询,按月查询每天数据,无数据自动填充0
先上代码,着急的同学直接复制就能用
之前写过一个按年查询每月数据,无数据自动填充0,需要的话点击这里。
查询语句
SELECT
DATE_FORMAT(lefttable.date, '%Y-%m') AS yearMonth,
lefttable.date
FROM
(
SELECT
ADDDATE(y. FIRST, x.d - 1) AS date
FROM
(
SELECT 01 AS d UNION ALL SELECT 02 UNION ALL SELECT 03 UNION ALL
SELECT 04 UNION ALL SELECT 05 UNION ALL SELECT 06 UNION ALL
SELECT 07 UNION ALL SELECT 08 UNION ALL SELECT 09 UNION ALL
SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL
SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL
SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL
SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL
SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL
SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL
SELECT 28 UNION ALL
SELECT 29 UNION ALL
SELECT 30 UNION ALL
SELECT 31
) x,
(
SELECT
CONCAT('2020-5', '-01') AS FIRST,
DAY (
LAST_DAY(
str_to_date('2020-5-2', '%Y-%m')
)
) AS last
) y
WHERE
x.d <= y.last
) AS lefttable
结果
2020-05-01
2020-05-02
2020-05-03
2020-05-04
2020-05-05
2020-05-06
2020-05-07
2020-05-08
2020-05-09
2020-05-10
2020-05-11
2020-05-12
2020-05-13
2020-05-14
2020-05-15
2020-05-16
2020-05-17
2020-05-18
2020-05-19
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
2020-05-30
2020-05-31
关键字
DATE_FORMAT(date,format)
DATE_FORMAT(date,format)
这个不用多说吧,都知道,日期格式化嘛
参数:
date: 日期
format: 格式('%Y-%m-%d')
DATE_ADD(date,INTERVAL expr unit)
定义:函数向日期添加指定的时间间隔。
参数:
date: 参数是合法的日期表达式
expr: 参数是您希望添加的时间间隔。
type 参数可以是下列值:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
示例
假设我们有如下的表:
OrderId | ProductName | OrderDate |
---|---|---|
1 | Computer | 2008-12-29 |
现在,我们希望向 “OrderDate” 添加 2 天,这样就可以找到付款日期。我们使用下面的 SELECT 语句:
SELECT
OrderId,
DATE_ADD(OrderDate,INTERVAL 2 DAY) AS OrderPayDate
FROM
Orders
结果:
OrderId | OrderPayDate |
---|---|
1 | 2008-12-31 |