根据created_at日期获取每月的运行总计
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据created_at日期获取每月的运行总计相关的知识,希望对你有一定的参考价值。
我正试图获得今年每个月的总计。所以我的理想结果将是:
January | 4
February | 5
March | 8
April | 10
May | 12
June | 14
July | 16
August | 17
September | 18
October | 21
November | 22
December | 22
基本计数只会在本月的第一天检查,例如:
January 1 (sum where created_at < January 1, 2018)
February 1 (sum where created_at < February 1, 2018)
March 1 (sum where created_at < March 1, 2018)
April 1 (sum where created_at < April 1, 2018)
...
一次做一个月很容易,因为我可以做这样的事情:
SELECT *
FROM businesses
WHERE created_at < CONCAT(YEAR(CURDATE()), "-12-01 00:00:01")
我尝试使用另一个来自另一个Stackoverflow答案的例子,但是它并没有像预期的那样工作,因为它看起来很混乱,所以计数没有正确排列。
您可以在此处查看架构构建和当前SQL:http://sqlfiddle.com/#!9/0c23cc/20
答案
尝试这样的事情。
SELECT
MONTHNAME( created_at ) AS theMonth,
(
SELECT
count( * )
FROM
businesses AS u1
WHERE
YEAR ( u1.created_at ) = YEAR ( businesses.created_at )
AND u1.created_at <= date_ADD( last_day( businesses.created_at ), INTERVAL 1 DAY )
) AS totals
FROM
businesses
WHERE
YEAR ( businesses.created_at ) = YEAR ( CURDATE( ) )
GROUP BY
MONTHNAME( businesses.created_at )
ORDER BY
MONTH ( businesses.created_at ) ASC
以上是关于根据created_at日期获取每月的运行总计的主要内容,如果未能解决你的问题,请参考以下文章
创建一个计算每月总收入的 PL/SQL 过程。总计必须按月打印