欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL实现按天统计数据的方法

程序员文章站 2022-05-17 16:13:59
一、首先生成一个日期表,执行SQL如下: 二、按天统计所需数据SQL如下: 以上统计数据可根据自身统计需求修改。 三、执行效果如下图: ......

一、首先生成一个日期表,执行sql如下:

create table num (i int);
insert into num (i) values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
create table  if not exists calendar(datelist date);  insert into calendar(datelist) select
    adddate(
        (   
            date_format("2019-1-1", '%y-%m-%d') 
        ),
        numlist.id
    ) as `date`
from
    (
        select
            n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000+ n10000.i * 10000 as id
        from
            num n1
        cross join num as n10
        cross join num as n100
        cross join num as n1000
        cross join num as n10000
    ) as numlist;

二、按天统计所需数据sql如下:

select
    date(dday) ddate,
    max(registernum) as registernum, 
    max(rechargenum) as rechargenum,
    max(rechargetotal) as rechargetotal
from
    (
        select
            datelist as dday,0 as registernum,0 as rechargenum,0 as rechargetotal
        from
            calendar 
            where  1  and date_sub(curdate(), interval 365 day) <= date(datelist)&&date(datelist)<=curdate()
        union all
            select  from_unixtime(a.time,"%y-%m-%d") as dday, 0 as registernum,count(distinct(a.user_id)) as rechargenum,sum(a.money) as rechargetotal from
               top_up as a left  join referee as b on a.user_id=b.referee_id
               left join channel_user as c on b.user_id = c.uid where 1  and c.uid=1087 and a.status=2
               group by dday  
         union all
            select  from_unixtime(a.time,"%y-%m-%d") as dday, count(a.referee_id) as registernum,0 as rechargenum,0 as rechargetotal from
               referee as a 
               left join channel_user as b on a.user_id = b.uid where 1  and b.uid=1087
               group by dday
    ) a
group by ddate
order by ddate desc limit 0,10

以上统计数据可根据自身统计需求修改。

三、执行效果如下图:

MySQL实现按天统计数据的方法