如何让这个查询工作“选择作为星期一week\u day where count(username)=(选择max(x.counts)from…”

ljsrvy3e  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(237)

用户表示例为:

select * from users limit 10;
+----+-----------------------+---------------------+
| id | username              | created_at          |
+----+-----------------------+---------------------+
|  1 | Kenton_Kirlin         | 2017-02-16 18:22:11 |
|  2 | Andre_Purdy85         | 2017-04-02 17:11:21 |
|  3 | Harley_Lind18         | 2017-02-21 11:12:33 |
|  4 | Arely_Bogan63         | 2016-08-13 01:28:43 |
|  5 | Aniya_Hackett         | 2016-12-07 01:04:39 |
|  6 | Travon.Waters         | 2017-04-30 13:26:14 |
|  7 | Kasandra_Homenick     | 2016-12-12 06:50:08 |
|  8 | Tabitha_Schamberger11 | 2016-08-20 02:19:46 |
|  9 | Gus93                 | 2016-06-24 19:36:31 |
| 10 | Presley_McClure       | 2016-08-07 16:25:49 |
+----+-----------------------+---------------------+
10 rows in set (0.00 sec)

以下查询工作正常:

SELECT DATE_FORMAT( created_at, '%W') AS week_day, COUNT(username) AS counts FROM users 
GROUP BY week_day ORDER BY counts DESC;
+-----------+--------+
| week_day  | counts |
+-----------+--------+
| Sunday    |     16 |
| Thursday  |     16 |
| Friday    |     15 |
| Monday    |     14 |
| Tuesday   |     14 |
| Wednesday |     13 |
| Saturday  |     12 |
+-----------+--------+
7 rows in set (0.00 sec)

以下第二个查询可以正常工作:

SELECT MAX(x.counts) FROM (SELECT DATE_FORMAT( u.created_at, '%W') AS week_day, COUNT(u.username) AS counts FROM users AS u GROUP BY week_day ORDER BY counts) AS x;
+---------------+
| MAX(x.counts) |
+---------------+
|            16 |
+---------------+
1 row in set (0.00 sec)

但是这个查询不起作用!!!!

SELECT DATE_FORMAT( created_at, '%W') AS week_day, COUNT(username) AS counts FROM users GROUP BY week_day WHERE COUNT(username) = (SELECT MAX(x.counts) FROM (SELECT DATE_FORMAT( u.created_at, '%W') AS week_da
y, COUNT(u.username) AS counts FROM users AS u GROUP BY week_day ORDER BY counts) AS x);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE COUNT(username) = (SELECT MAX(x.counts) FROM (SELECT DATE_FORMAT( u.create' at line 1

我已经尝试了许多替代方案,但仍然不起作用其中一个是2=。。。。。。其中计数=。。。。。。
我怎样才能解决这个问题?我需要做的是动态地生成日期名称,其中包含在这些日期创建的最大用户数,比如

+----------+--------+
| week_day | counts |
+----------+--------+
| Sunday   |     16 |
| Thursday |     16 |
+----------+--------+
htrmnn0y

htrmnn0y1#

绝对不是最简单的方法来做你想做的,但是你的语法问题是没有使用 HAVING 条款:

SELECT DATE_FORMAT( created_at, '%W') AS week_day, COUNT(username) AS counts
FROM users
GROUP BY week_day 
HAVING COUNT(*) = (SELECT MAX(x.counts)
                   FROM (SELECT DATE_FORMAT( u.created_at, '%W') AS week_da
y, COUNT(u.username) AS counts 
                         FROM users u
                         GROUP BY week_day 
                        ) x
                  );

相关问题