MySQL按年度分组的结果正在发生变化

MySQL按年度分组的结果正在发生变化,mysql,sql,Mysql,Sql,我有一个SQL语句,它选择一系列值,然后按年/月/日对它们进行分组。这似乎效果不错 真正令人困惑的是,如果我在第二天运行这个SQL,结果数字就会改变。我认为总的来说,这些数字是正确的,但是当在不同的日子运行时,它们会改变一到两个 例如 第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

我有一个SQL语句,它选择一系列值,然后按年/月/日对它们进行分组。这似乎效果不错

真正令人困惑的是,如果我在第二天运行这个SQL,结果数字就会改变。我认为总的来说,这些数字是正确的,但是当在不同的日子运行时,它们会改变一到两个

例如

第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的。我错过了什么?我假设使用GROUPBY函数时出现计数错误,但我不知道是什么

注意。 该SQL由cronjob每天早上运行。不是手工操作,所以我不认为用户错误是罪魁祸首(除了在创建语句时)

编辑:
很抱歉,打印的SQL中有一个错误(我为公众稍微修改了一下)。应该在每个地方开始。这个问题仍然存在

为什么按
startDate
分组,但输出
purchaseDate
(日期格式(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");

有几件事。首先,是否真的可以有一个
startDate>=now()的记录?这不应该造成你的问题,但我觉得没有必要。其次,您的
groupby
子句将分组到每个唯一的日期,那么为什么不简单地使用
groupby-DATE(startDate)

这两个建议将把您的查询简化为

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"
GROUP BY DATE(startDate);

这些更改改进了您的查询,但此版本和原始版本的结果每天都不应变化。所有已更改的结果显示的记录较少,因此我猜用户正在删除记录。

可能其中一个历史条目的起始日期是错误的年份!?!?为什么不向我们提供表格和样本数据呢如果您使用的是开始日期,则按开始日期分组,或者按产品日期分组。我将尝试您的第一个示例,使用按日期分组格式(startDate,“%Y-%m-%d”)@winna欢迎使用堆栈溢出。如果这个答案对你有用,请
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");
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");
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"
GROUP BY DATE(startDate);