按周开始的组查询结果

时间:2015-09-28 17:46:17

标签: php mysql

我有几个不同的表格,我试图加入汇总结果,并根据不同的时间间隔对它们进行分组。

calendar table
+------------+
| adate      |
+------------+
| 2015-09-24 |
| 2015-09-25 |
| 2015-09-26 |
| 2015-09-27 |
| 2015-09-28 |
....etc.......

plays table
+----+------------+----------+---------------------+---------------------+
| id | session_id | video_id | created_at          | updated_at          |
+----+------------+----------+---------------------+---------------------+
|  1 |          1 |        1 | 2015-09-25 15:49:50 | 2015-09-25 15:49:50 |
+----+------------+----------+---------------------+---------------------+

PHP / SQL:

switch ( TRUE ) {
  case ($interval->days <= 7):
  default:
    $group_by = 'DATE(dates.adate)';
    break;
  case in_array( $interval->days, range(8, 31) ):
    $group_by = 'CONCAT(YEAR(dates.adate), "/", WEEK(dates.adate))';
    break;
  case ($interval->days > 31):
    $group_by = 'YEAR(dates.adate), MONTH(dates.adate)';
    break;
}

$sql = '
  SELECT calendar.adate,
         IFNULL(g.event_count, 0) event_count
  FROM calendar
  LEFT JOIN (
    SELECT DATE(events.created_at) created_at,
           COUNT(*) event_count
    FROM plays events
    WHERE events.video_id = %d
    AND   events.created_at >= %s
    AND   events.created_at < date_add(%s, INTERVAL 1 DAY)
    GROUP BY DATE(events.created_at)
  ) g
  ON g.created_at = calendar.adate
  WHERE calendar.adate BETWEEN %s AND %s
  GROUP BY ' . $group_by . '
  ORDER BY adate;
';

我想根据间隔长度更改分组,即。如果它是一周的结果然后每天分组,那么一个月的结果应该按照9/28/15周的分组进行,一年的结果应该分组by mm / yyyy

您能说明如何对结果集进行相应分组吗?我觉得我很亲密,但在这里遗漏了一些东西。

0 个答案:

没有答案