1

I have an SQL statement that selects a range of values and then groups them by year/month/day. This appears to work fine.

What is really confusing, is that if I run this SQL on the next day, the result numbers change. I think overall, the numbers are correct, but they change by one or two when run on different days.

eg.

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);

Results on Day 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

Results on Day 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

Notice how on 27.12.2012 and 30.12.2012 the result are off by one. What am I missing? I assume there is a counting error using the Group by functions, but I don't know what.

NB. This SQL is run by a cronjob each day in the morning. Not by hand, so I don't think user error is to blame here (except in the creation of the statement).

EDIT: Sorry, there was a mistake in the printed SQL (I changed it slightly for the public). It should be startDate every where. The issue still stands.

4

2 回答 2

0

有几件事。首先,真的可以有记录startDate >= now()吗?这不应该导致您遇到的问题,但我只是不认为需要它。其次,您的GROUP BY子句将分组到每个独特的日子,那么您为什么不简单地使用GROUP BY 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);

这些更改改进了您的查询,但无论是此版本还是您的原始版本的结果都不应在日常基础上有所不同。所有改变的结果都显示更少的记录,所以我猜用户正在删除记录。

于 2013-01-14T13:52:14.523 回答
0

为什么你分组startDate但输出purchaseDate (Date_format(purchaseDate, "%Y-%m-%d"))PurchaseDateMySQL 将为每个组选择什么?

我认为您的 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");
于 2013-01-14T12:44:14.447 回答