1

我正在尝试查询以获取特定月份每天的高峰时间。我的表如下所示:

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

4 回答 4

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;
于 2012-06-29T20:39:53.817 回答
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

于 2012-06-29T20:34:25.893 回答
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);
于 2012-06-29T20:31:55.377 回答
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 将数据放在那里。

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

于 2012-06-29T20:56:39.573 回答