gpt4 book ai didi

mysql - 计算每个帐户组的记录数量,其中加入日期 = 每个月

转载 作者:行者123 更新时间:2023-11-29 00:19:15 25 4
gpt4 key购买 nike

我有一个表(帐户),其中包含帐户组和帐户加入日期,以及其他字段。使用 MySQL 版本 5.5.35-cll。

本质上,我要做的是计算每个帐户组每个月发生的“注册”数量。 (不仅仅是每月的总金额 - 需要知道每个帐户组中每个月发生了多少注册)。

所以结果看起来像这样:

intended results http://imageshack.com/a/img842/9105/drh9.gif

我尝试了几种不同的方法,但只成功地获得了指定月份的所需内容,而不是一年中的所有月份。当我尝试使用 SUM 时,它看起来好像在工作,但没有按预期工作 - 似乎它认为每个组每月最多有 1 个注册,而实际上至少有 4 或 5 个一些团体。

这是我最近一次(失败)的 SUM 尝试:

SELECT accountgroup, 
SUM( IF( MONTH =1, numRecords, 0 ) AND YEAR=2014) AS 'January',
SUM( IF( MONTH =2, numRecords, 0 ) AND YEAR=2014) AS 'February',
SUM( IF( MONTH =3, numRecords, 0 ) AND YEAR=2014) AS 'March',
SUM( IF( MONTH =4, numRecords, 0 ) AND YEAR=2014) AS 'April',
SUM( IF( MONTH =5, numRecords, 0 ) AND YEAR=2014) AS 'May',
SUM( IF( MONTH =6, numRecords, 0 ) AND YEAR=2014) AS 'June',
SUM( IF( MONTH =7, numRecords, 0 ) AND YEAR=2014) AS 'July',
SUM( IF( MONTH =8, numRecords, 0 ) AND YEAR=2014) AS 'August',
SUM( IF( MONTH =9, numRecords, 0 ) AND YEAR=2014) AS 'September',
SUM( IF( MONTH =10, numRecords, 0 ) AND YEAR=2014) AS 'October',
SUM( IF( MONTH =11, numRecords, 0 ) AND YEAR=2014) AS 'November',
SUM( IF( MONTH =12, numRecords, 0 ) AND YEAR=2014) AS 'December',
SUM( numRecords ) AS total
FROM (
SELECT accountgroup, MONTH( joineddate ) AS MONTH, YEAR( joineddate ) AS YEAR, COUNT( * ) AS numRecords
FROM accounts
WHERE accountgroup <>''
GROUP BY accountgroup, MONTH, YEAR) AS SubTable1
GROUP BY accountgroup");

谁能告诉我怎么做?我很困惑:(
在此先感谢您的帮助。

最佳答案

你们很亲近。您需要将 year 条件放在 if 中。例如:

SUM(IF(MONTH = 1 AND YEAR = 2014, numRecords, 0)) AS January, 
SUM(IF(MONTH = 2 AND YEAR = 2014, numRecords, 0)) AS February,
. . .

您不需要最后的括号。因此,查询应如下所示:

SELECT accountgroup, 
SUM(IF(MONTH = 1 AND YEAR = 2014, numRecords, 0)) AS January,
SUM(IF(MONTH = 2 AND YEAR = 2014, numRecords, 0)) AS February,
. . .
SUM( numRecords ) AS total
FROM (SELECT accountgroup, MONTH( joineddate ) AS MONTH, YEAR( joineddate ) AS YEAR, COUNT( * ) AS numRecords
FROM accounts
WHERE accountgroup <>''
GROUP BY accountgroup, MONTH, YEAR
) AS SubTable1
GROUP BY accountgroup";

另外,不要在应该是列名或表名的东西上使用单引号。在这种情况下,您不需要转义这些名称。使用双引号或反引号。仅对字符串和日期常量使用单引号。

关于mysql - 计算每个帐户组的记录数量,其中加入日期 = 每个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21733761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com