mysql计算近n天近n个月分组,如果为空补全的解决方案

mysql计算近n天近n个月分组,如果为空补全的解决方案,第1张

1.近n个月 

不废话 直接上sql

SELECT

DATE_FORMAT( @cdate := DATE_ADD( @cdate, INTERVAL - 1 MONTH ), '%Y-%m' ) AS cmonth

FROM

( SELECT @cdate := DATE_ADD( '2020-7-1', INTERVAL + 1 MONTH ) FROM information_schema.CHARACTER_SETS ) t0

LIMIT 100

注意 information_schema.CHARACTER_SETS这个表是mysql系统表,可以取到的最大月数和这个表的数量有关,如果又更多的时间要选,可以查询其他表,数据量不要太大,太大会影响查询效率

2 同理 上近n天

SELECT

@cdate := DATE_ADD( @cdate, INTERVAL - 1 DAY )AS DAYS

FROM

( SELECT @cdate := DATE_ADD( '2020-7-1', INTERVAL + 1 DAY ) FROM information_schema.CHARACTER_SETS ) t0

LIMIT 100

可以加个时间维度表,以时间维度表为主表!(id,month)id 是和你的表左连接,month是1到12月,一楼说的几个方法!应该不好实现的吧?不用写存储过程那么复杂!举个例子

select a.rq,

b.xssr

from date_table a left jion table1 b

on a.id=b.id

一、打开MySQL工具,我用的是Navicat Premium

二、新建查询,输入sql命令

举例如下:

分组查询

1、年度分组

2、月度分组

3、先按年度分组,再按月度分组

4、按年月分组

SELECT count(ArticleId), date_format(FROM_UNIXTIME( `BlogCreateTime`),'%y%m') sdate FROM `blog_article` group by sdate

结果:

count( ArticleId ) sdate

17 0901

11 0902

5 0903

6 0904

2 0905

1 0907

12 0908

6 0909

11 0910

3 0911

其他方法参考:

我想做一个统计,数据库是mysql,统计出每天,每周,每月的记录数

建表的时候加个字段表示日期,然后查sql手册...

select count(*) from `table` where `date`='{某天}'

select count(*) from `table` where date_format(`date`,'%V')='{某周}'

select count(*) from `table` where date_format(`date`,'%c')='{某月}'

另一种方法:

select count( * ) from projects where editdate >= '2007-11-9 00:00:00' and editdate <=

'2007-11-9 24:00:00'

第三种方法:

每周的

SQL codeselect count(*) as cnt,week(editdate) as weekflg from projects where year(editdate)

=2007 group by weekflg

每月

SQL codeselect count(*) as cnt,month(editdate) as monthflg from projects where year

(editdate)=2007 group by monthflg

每天

SQL codeselect count(*) as cnt from projects group by date(editdate)

mysql中DATE_FORMAT(date, format)函数可根据format字符串格式化日期或日期和时间值date,返回结果

串。

也可用DATE_FORMAT( ) 来格式化DATE 或DATETIME 值,以便得到所希望的格式。根据format字符串格式

化date值:

下面是函数的参数说明:

%S, %s 两位数字形式的秒( 00,01, . . ., 59)

%i 两位数字形式的分( 00,01, . . ., 59)

%H 两位数字形式的小时,24 小时(00,01, . . ., 23)

%h, %I 两位数字形式的小时,12 小时(01,02, . . ., 12)

%k 数字形式的小时,24 小时(0,1, . . ., 23)

%l 数字形式的小时,12 小时(1, 2, . . ., 12)

%T 24 小时的时间形式(hh : mm : s s)

%r 12 小时的时间形式(hh:mm:ss AM 或hh:mm:ss PM)

%p AM 或P M

%W 一周中每一天的名称( Sunday, Monday, . . ., Saturday)

%a 一周中每一天名称的缩写( Sun, Mon, . . ., Sat)

%d 两位数字表示月中的天数( 00, 01, . . ., 31)

%e 数字形式表示月中的天数( 1, 2, . . ., 31)

%D 英文后缀表示月中的天数( 1st, 2nd, 3rd, . . .)

%w 以数字形式表示周中的天数( 0 = Sunday, 1=Monday, . . ., 6=Saturday)

%j 以三位数字表示年中的天数( 001, 002, . . ., 366)

% U 周(0, 1, 52),其中Sunday 为周中的第一天

%u 周(0, 1, 52),其中Monday 为周中的第一天

%M 月名(January, February, . . ., December)

%b 缩写的月名( January, February, . . ., December)

%m 两位数字表示的月份( 01, 02, . . ., 12)

%c 数字表示的月份( 1, 2, . . ., 12)

%Y 四位数字表示的年份

%y 两位数字表示的年份

%% 直接值“%”


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/8510991.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-17
下一篇 2023-04-17

发表评论

登录后才能评论

评论列表(0条)

保存