我有一个 SQL 语句,它选择一系列值,然后按年/月/日对它们进行分组。这似乎工作正常。
真正令人困惑的是,如果我在第二天运行此 SQL,结果数字会发生变化。我认为总的来说,数字是正确的,但在不同的日子运行时,它们会发生一两个变化。
例如。
select Date_format(startDate, "%Y-%m-%d") as Date, count(*) as Online
from
`promotion` p, `subscription` s
where
p.`uid` = s.`uid` and
s.`productId` = "groupproduct"
startDate < now()
GROUP BY YEAR(startDate), MONTH(startDate), DAYOFMONTH(startDate);
第 X 天的结果
2012-12-25 265
2012-12-26 264
2012-12-27 232
2012-12-28 187
2012-12-29 171
2012-12-30 8935
2012-12-31 3117
第 X+1 天的结果
2012-12-25 265
2012-12-26 264
2012-12-27 231
2012-12-28 187
2012-12-29 171
2012-12-30 8933
2012-12-31 3114
请注意 2012 年 12 月 27 日和 2012 年 12 月 30 日的结果相差 1。我错过了什么?我假设使用 Group by 函数时出现计数错误,但我不知道是什么原因。
注意。 此 SQL 由 cronjob 每天早上运行。不是手工操作,所以我不认为用户错误是这里的罪魁祸首(除了创建语句)。
编辑: 抱歉,打印的 SQL 有错误(我为公众稍微修改了一下)。每个地方都应该是 startDate。问题依然存在。
最佳答案
为什么按startDate
分组却输出purchaseDate
(Date_format(purchaseDate, "%Y-%m-%d"))
. MySQL 将为每个组选择什么 PurchaseDate
?
我认为您的 SQL 应该如下所示:
select Date_format(startDate, "%Y-%m-%d") as Date, count(*) as Online
from
`promotion` p, `subscription` s
where
p.`uid` = s.`uid` and
s.`productId` = "groupproduct"
startDate < now()
GROUP BY Date_format(startDate, "%Y-%m-%d");
或者如果您需要 purchaseDate
select Date_format(purchaseDate, "%Y-%m-%d") as Date, count(*) as Online
from
`promotion` p, `subscription` s
where
p.`uid` = s.`uid` and
s.`productId` = "groupproduct"
startDate < now()
GROUP BY Date_format(purchaseDate, "%Y-%m-%d");
关于MySQL Group By Year 结果正在改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14318048/