Jeremy Smith
Jeremy Smith

Reputation: 15069

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. I'd like to have the dates 7 days apart, preferably starting on the Monday of each week.

Upvotes: 1

Views: 1680

Answers (2)

maxtwoknight
maxtwoknight

Reputation: 5346

To expand on my comment

SELECT STR_TO_DATE(concat(year(fulfilled_at), 
    weekofyear(fulfilled_at),' Monday'), '%X%V %W')
from purchases 

A fiddle to demo

Upvotes: 2

km6zla
km6zla

Reputation: 4877

This is because you are not specifying which fulfilled_at to select from the set grouped by YEAR(fulfilled_at), WEEKOFYEAR(fulfilled_at). In that set there are n number of fulfilled_at dates and MySQL just selects the first one.

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.

I also notice that in your GROUP BY clause you are using the WEEKOFYEAR function but your select is using the WEEK function. 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.

From MySQL Documentation on WEEKOFYEAR

WEEKOFYEAR(date)

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

Upvotes: 0

Related Questions