SQL:我用select max()搜索好查询并选择count()

时间:2015-02-14 15:25:23

标签: mysql sql select count max

我有一个名为到达的表格(这个表很简单,它只是保存那些在这样的一天和那个时间到达学校的用户),并附有以下数据:

id  name    day         hour
1   Alice   Monday      11
2   Alice   Monday      13
3   Alice   Tuesday     11
4   Céline  Wednesday   14
5   Céline  Wednesday   13
6   Céline  Thursday    14
7   Maud    Friday      15
8   Maud    Saturday    15
9   Maud    Saturday    16

现在,我搜索为每个用户查找的好查询:最频繁的一天和最频繁的小时,也就是说,查询的结果必须返回以下行:

Alice   Monday      11
Céline  Wednesday   14
Maud    Saturday    15

=>因为:

  • 爱丽丝经常在周一到达,经常在11点
  • Céline经常在周三到达,经常在14h
  • Maud经常在周六到达,经常在15h

我的查询如下,但它没有给我带来好结果:

SELECT NAME,
       day,
       Max(count_hour)
FROM   (SELECT NAME,
               day,
               Count(hour) AS count_hour
        FROM   arrived
        GROUP  BY NAME,
                  day) AS alias_table
GROUP  BY NAME 

亲切地谢谢你。

2 个答案:

答案 0 :(得分:0)

选择列时尝试greatest(day, hour)。您也可以尝试greatest(max(day), max(hour))

干杯!

答案 1 :(得分:0)

不确定这是否正确,但应该有效!

SELECT *
FROM   arrived A
WHERE  hour = (SELECT hour
               FROM   arrived B
               WHERE  a.NAME = b.NAME
               GROUP  BY b.hour,
                         b.NAME
               ORDER  BY Count(b.hour) DESC Limit 1)
       AND day = (SELECT day
                  FROM   arrived B
                  WHERE  a.NAME = b.NAME
                  GROUP  BY b.day,
                            b.NAME
                  ORDER  BY Count(b.day) DESC Limit 1) 

SQLFIDDLE DEMO