开发者

Getting week started date using MySQL

If I have MySQL query like this, summing word frequencies per week:

SELECT 
  SUM(`city`), 
  SUM(`officers`), 
  SUM(`uk`), 
  SUM(`wednesday`), 
  DATE_FORMAT(`dateTime`, '%d/%m/%Y') 
FROM myTable 
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00' 
GROUP BY WEEK(dateTime开发者_StackOverflow)

The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.

Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?

The dateTime column is in format 2011/10/02 12:05:00


It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜