gpt4 book ai didi

mysql - SQL : I search the good query with select max() and select count()

转载 作者:行者123 更新时间:2023-11-30 22:49:42 25 4
gpt4 key购买 nike

我有一个名为arrived的表(这个表很简单,它只保存了在某天某时到达学校的用户),其中包含以下数据:

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

=> 因为:

  • Alice 经常在星期一到达,而且经常在 11 点到达
  • Céline 经常在星期三到达,而且经常在 14 点到达
  • Maud 经常在周六到达,而且经常在 15 点到达

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

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

谢谢你,诚挚的。

最佳答案

不确定这样做是否正确,但应该可行!

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

关于mysql - SQL : I search the good query with select max() and select count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com