一个月内每天的高峰时间表MySQL

时间:2012-06-29 20:23:20

标签: mysql reporting

我正在尝试查询特定月份的每日高峰时段。 我的表格看起来像这样:

id      idproduct       created_at
1       021354684       2011-10-01 20:25:48
2       033546835       2011-10-01 20:30:15
3       055965654       2011-10-01 20:45:20
4       012975343       2011-10-02 14:03:36
5       021354684       2011-10-02 15:55:48
6       033546835       2011-10-02 16:30:15
7       055965654       2011-10-02 16:45:20
8       012975343       2011-10-02 18:53:36
9       021354684       2011-10-03 08:55:48
10      033546835       2011-10-03 09:30:15
11      055965654       2011-10-03 14:03:20
12      012975343       2011-10-03 14:03:36

我试图获得的是这样的......:

day     rush_hour    number_of_rows
1       20:00        3
2       16:00        5
3       14:00        4

是否可以获得这样的表格?你能帮助我吗?

我犯了一个错误,对不起。行数应该是当天销售的商品总数,而不是那个小时:(抱歉。

4 个答案:

答案 0 :(得分:3)

http://sqlfiddle.com/#!2/5b87b/7

首先,计算每一天每小时的计数(进入视图,因为我们将在下面使用它两次):

CREATE VIEW hours AS 
SELECT
  DATE( created_at ) AS d,
  HOUR( created_at ) AS h,
  COUNT(*) AS c
FROM item
GROUP BY DATE(created_at), HOUR(created_at);

最终查询:

SELECT
  hours.d AS `day`,
  hours.h AS `rush_hour`,
  hours.c AS `count`

-- get the max count for every day
FROM (
      SELECT
        d,          -- the day 
        MAX(c) as c -- the count
      FROM hours
      GROUP BY d
     ) AS maxc

-- find the actual hour(s) with the max count for every day:
INNER JOIN hours ON hours.c = maxc.c
                AND hours.d = maxc.d;

答案 1 :(得分:2)

您想要查看MySQL Date Functions,他们会为您提供一些帮助

SELECT 
  day(created_at) as day, 
  hour(created_at) as rush_hour, 
  count(1) as num_rows 
FROM item
GROUP BY
  day(created_at), hour(created_at)

http://sqlfiddle.com/#!2/62a15/2/0

答案 2 :(得分:0)

试试这个:

SELECT dayofyear(created_at) as day, hour(created_at) as rush_hour, count(*) as number_of_rows 
FROM table
GROUP BY dayofyear(created_at), hour(created_at);

答案 3 :(得分:0)

这里没有观点:

SELECT ddd.day, eee.rush_hour, ddd.maxo
FROM 
(select day, max(num_rows) as maxo from (
SELECT 
  day(created_at) as day, 
  hour(created_at) as rush_hour, 
  count(1) as num_rows 
FROM item
GROUP BY
  day(created_at), hour(created_at)
  ) as groupo group by day) as ddd

LEFT JOIN
(SELECT 
  day(created_at) as day, 
  hour(created_at) as rush_hour, 
  count(1) as num_rows 
FROM item
GROUP BY
  day(created_at), hour(created_at)
  ) as eee on ddd.day=eee.day and ddd.maxo=eee.num_rows

我可以想象它格式化得更好或者有更多相关的别名,但这里有很多次选择。

感谢SQLfiddlers将数据放在那里。

而且我认为,如果你有两个小时并没有计算出你所计算的最高数量,它们都会出现,所以你会得到两个(或更多)的记录,这个月的那天。