MySQL - 制作每周报告,包括开始日(扭曲:周三开始)

时间:2014-11-13 15:06:38

标签: mysql aggregate

我有这种基于时间的数据表:

| entity_id | ttime               | value |
-------------------------------------------
|         1 | 2014-11-01 00:00:04 |   553 |
|         1 |                 ... |   600 |
|         2 |                 ... |   234 |

我想获得按周和entity_id分组的值的平均值。但我也想在本周的开始日出现在结果中。更复杂的是本周开始于周三。

我可以按年份(ttime + INTERVAL 3天),周(ttime + INTERVAL 3天)分组,但是可以在结果中打印小组的第一天(周三)吗?

由于

2 个答案:

答案 0 :(得分:1)

可能是这样的:

SELECT 
 `entity_id`, 
  DATE_SUB(ttime, INTERVAL WEEKDAY(ttime)-2 DAY),
  SUM(`value`)  
FROM `table` 
GROUP BY `entity_id`, YEARWEEK(ttime + INTERVAL 4 DAY)

SqlFiddle

答案 1 :(得分:0)

我找到了这个解决方案:

SELECT
str_to_date(CONCAT(YEAR(ttime + INTERVAL -3 DAY), 
           WEEK(ttime + INTERVAL -3 DAY), 'Wednesday'), '%X%V %W') as WeekCommencing,
           entity_id, AVG(value), 
FROM `table`
GROUP BY WeekCommencing, entity_id