查询近7天,近1个月,近3个月每天的数据量,查询近一年每个月的数据量

统计近7天每天,近一个月每天,近三个月每天,近一年每个月的新增数量,用于画折线图,由于是根据create_time字段统计的,所以如果有一天没有新增,就会缺少这一天的日期,要对日期进行补充,当天没有新增的new_count置为0,所以要建立一个日期表calendar

1、查询单表account,近7天每天新增的数量

SELECT
IFNULL(COUNT(a.create_time), 0) AS new_count,
DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) AS show_time 
FROM
account a
RIGHT JOIN calendar c ON DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) = DATE_FORMAT(a.create_time, ‘%Y-%m-%d‘)  WHERE c.datelist < CURDATE()
AND c.datelist >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY
show_time
ORDER BY
show_time ASC;


2、查询单表account近一个月每天、近三个月每天的数据量写法同上

3、查询近一年每个月的数据量

SELECT
    IFNULL(count(a.create_time), 0) AS new_count,
    DATE_FORMAT(c.datelist, ‘%Y-%m‘) AS show_time
FROM
    account a
RIGHT JOIN calendar c ON DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) = DATE_FORMAT(a.create_time, ‘%Y-%m-%d‘)
WHERE
    c.datelist < CURDATE()
AND c.datelist >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
GROUP BY
    show_time
ORDER BY
    show_time ASC;


4、查询近7天,account表字段为reward符合日期查询条件的total reward

SELECT
IFNULL(SUM(reward), 0) AS reward,
DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) AS show_time
FROM
account a
RIGHT JOIN calendar c ON DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) = DATE_FORMAT(a.create_time, ‘%Y-%m-%d‘)
WHERE
c.datelist < CURDATE()
AND c.datelist >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY
show_time
ORDER BY
show_time ASC;


(查询近一个月每天,近三个月每天的total reward同上)

5、查询近一年每个月的total reward

SELECT
IFNULL(SUM(reward), 0) AS reward,
DATE_FORMAT(c.datelist, ‘%Y-%m‘) AS show_time
FROM
account a
RIGHT JOIN calendar c ON DATE_FORMAT(c.datelist, ‘%Y-%m-%d‘) = DATE_FORMAT(a.create_time, ‘%Y-%m-%d‘)
WHERE
c.datelist < CURDATE()
AND c.datelist >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
GROUP BY
show_time
ORDER BY
show_time ASC;
————————————————
版权声明:本文为CSDN博主「YJ2」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/y_1111/article/details/78971291