[英]MySQL - How do I aggregate by week and select the first day of the week?
With this query: 使用此查询:
SELECT
fulfilled_at,
ROUND(SUM(adjusted_total_charge), 2) as val,
WEEK(fulfilled_at) as week
FROM purchases
WHERE fulfilled_at >= '2013-02-23 16:59:54 -0500'
AND fulfilled_at <= '2013-05-22 16:59:54 -0400'
GROUP BY YEAR(fulfilled_at), WEEKOFYEAR(fulfilled_at)
ORDER BY fulfilled_at ASC
I get this result: 我得到这个结果:
2013-02-24 14:03:29 5570.00 8
2013-02-27 04:15:46 67354.25 8
2013-03-05 13:53:28 45298.00 9
2013-03-11 13:54:59 40751.80 10
2013-03-18 16:12:27 42863.25 11
2013-03-27 14:16:25 35449.45 12
2013-04-02 13:23:58 46326.75 13
2013-04-08 05:25:55 35905.45 14
2013-04-15 15:50:12 28910.19 15
2013-04-22 18:42:10 31960.00 16
2013-04-29 23:37:51 36610.10 17
2013-05-06 15:57:23 24511.40 18
2013-05-16 22:32:29 20675.20 19
2013-05-20 18:17:49 9343.00 20
Notice that the fulfilled_at that is being shown is not from a specific day of the week, so the intervals are not an even 7 days apart. 请注意,所显示的fulfilled_at并非来自一周的特定日期,因此间隔之间的间隔甚至不是7天。 I'd like to have the dates 7 days apart, preferably starting on the Monday of each week.
我想将日期分开7天,最好从每周的星期一开始。
This is because you are not specifying which fulfilled_at
to select from the set grouped by YEAR(fulfilled_at), WEEKOFYEAR(fulfilled_at)
. 这是因为你没有指定其
fulfilled_at
从由分组设定选择YEAR(fulfilled_at), WEEKOFYEAR(fulfilled_at)
In that set there are n
number of fulfilled_at
dates and MySQL just selects the first one. 在该集合中,有
n
个fulfilled_at
日期,而MySQL只选择第一个。
You could only have them be 7 days apart if there happens to be a fulfilled_at
date on the first day of each week. 如果每个星期的第一天碰巧有一个
fulfilled_at
日期,那么您只能让它们相隔7天。
I also notice that in your GROUP BY
clause you are using the WEEKOFYEAR
function but your select is using the WEEK
function. 我还注意到,在
GROUP BY
子句中,您正在使用WEEKOFYEAR
函数,但是您的选择正在使用WEEK
函数。 Is that intentional? 那是故意的吗? The
WEEK(date[,mode])
function allows you to specify which day of the week is considered to be the first, a mode value of 1 being Monday. WEEK(date[,mode])
函数允许您指定一周中的哪一天被认为是第一天,模式值为1表示星期一。
From MySQL Documentation on WEEKOFYEAR 从WEEKOFYEAR的MySQL文档中
WEEKOFYEAR(date)
WEEKOFYEAR(日期)
Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
以1到53之间的数字形式返回日期的日历周。WEEKOFYEAR()是一个兼容函数,等效于WEEK(date,3)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.