mysql最近7天销售额_mysql查询近七天、近三十天、近年(按月份)的所有统计数据...

目录

在做统计表的时候,需要用mysql查询近7天的数据,当某一天数据为0的时候也需要返回

主要用到:

infull函数

union

interval函数

date_sub函数infull函数:infull() 函数用于判断第一个表达式是否为 null,如果为 null 则返回第二个参数的值,如果不为 null 则返回第一个参数的值。

union:union操作符用于合并两个或多个 select 语句的结果集。

interval函数:interval()函数将N个列表(N1,N2,N3,等等)的值进行比较。该函数返回0如果N

date_sub函数: date_sub() 函数从日期减去指定的时间间隔

一、查询近七天、近三十天

SELECT a.item,IFNULL(b.value,0) AS value

FROM (

SELECT CURDATE() AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 3 DAY) AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 4 DAY) AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 5 DAY) AS item

UNION ALL

SELECT DATE_SUB(CURDATE(), INTERVAL 6 DAY) AS item

) a LEFT JOIN (

SELECT DATE(create_time) AS date, count(date_format(create_time,'%Y-%m-%d')) AS value

FROM b_statistic

GROUP BY DATE(create_time)

) b ON a.item = b.date;

58f30234b0baf05e7f37d7253a437a02.png

近三十天可以给加到 SELECT DATE_SUB(CURDATE(), INTERVAL 29 DAY) AS item

二、查询近年,即十二个月的数据

SELECT

tab.month as item,

ifnull(va.value, 0) as value

FROM

(SELECT

date_format( date_sub( curdate( ), INTERVAL t.count MONTH ), '%Y-%m' ) AS MONTH

FROM

(

SELECT

t.c AS count

FROM

(

SELECT

0 AS c UNION

SELECT

1 AS c UNION

SELECT

2 AS c UNION

SELECT

3 AS c UNION

SELECT

4 AS c UNION

SELECT

5 AS c UNION

SELECT

6 AS c UNION

SELECT

7 AS c UNION

SELECT

8 AS c UNION

SELECT

9 AS c UNION

SELECT

10 AS c UNION

SELECT

11 AS c

) t

) AS t) tab

LEFT JOIN (

SELECT

DATE_FORMAT(b.create_time, '%Y-%m') as item,

count(DATE_FORMAT(b.create_time, '%Y-%m')) as value

FROM

b_statistic b

WHERE

DATE_FORMAT(b.create_time, '%Y-%m') > DATE_FORMAT(

date_sub(curdate(), INTERVAL 12 MONTH),

'%Y-%m'

)

GROUP BY

item

) va ON tab.month = va.item

8272b371dc1890f620290e768b8e221c.png

本文地址:https://blog.csdn.net/qq_41937388/article/details/107391926

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值