按周计算最近4周的记录

时间:2015-09-29 03:58:44

标签: php mysql

我需要一个查询,允许我从MySQL表中选择最近4周的数据,但输出为从4周前的星期一开始的天数,而不管当周的当天。

DB有一个用户表,一个活动表,其FK为userID。 具有FK到activityID

的activityStats表

该查询将用于创建类似于:

的数组
$array = [
   "userid" => "userid",
   "dateAdded" => "dateAdded",
   "week1" => $array = [
      "monday" => $array = [
         "activityid" => "1",
         "time" => "21",
         ...
      ]
      "tuesday" => $array = [
         "activityid" => "2",
         "time" => "16",
         ...
      ]
      "wednesday" => $array = [
         "activityid" => "3",
         "time" => "16",
         ...
      ]
      ...
   "week2" => $array = [
      "monday" => $array = [
         "activityid" => "8",
         "time" => "21",
         ...
      ]
      "tuesday" => $array = [
         "activityid" => "9",
         "time" => "16",
         ...
      ]
      "wednesday" => $array = [
         "activityid" => "10",
         "time" => "16",
         ...
      ]
      ...
   ]
   ...
];

我可以创建多个查询,但这可能需要10周,或52周,而单独的查询可能不会削减它。

不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

假设您的时间戳列被称为timestamp,您可以:

SELECT CONCAT(YEAR(timestamp), '/', WEEK(timestamp)) AS week

然后检索特定范围,按周排序等。