给定名为USERS_FAKE U的表,我需要编写一个查询来查找最常用的名字。
我的问题是,我仅设法编写了一个仅返回1个公用名的查询。但是,如果名称“ Bob”显示6次,使其成为最常见的名字,并且还有其他名称显示6次(例如“ Mike”),我的查询将仅返回“ Bob”。我的查询应返回Bob,Mike以及其他与最高频率出现次数相同的名称。
我设法将查询分为2个块,但是很难用可接受的SQL语法将其组合在一起。
第一个块查找的是TOP频率,即表中所有名称的最高出现次数。该查询在这里,它返回一个数字(例如:6)
(SELECT DISTINCT COUNT(FIRST_NAME) AS TOP_NAME_FREQUENCY
FROM
(SELECT FIRST_NAME, COUNT(FIRST_NAME) AS NUM_NAMES
FROM USERS_FAKE U
GROUP BY FIRST_NAME
ORDER BY NUM_NAMES DESC));
然后,第二个块将仅简单地将具有等于EQUAL的频率的名称返回到上述查询,将其前置在ABOVE查询之前。
整个组合查询看起来像这样:
SELECT DISTINCT FIRST_NAME, COUNT(FIRST_NAME) AS MOST_FREQUENCY //1st chunk starts
FROM USERS_FAKE U
WHERE COUNT(FIRST_NAME) AS MOST_FREQUENCY =
(SELECT DISTINCT COUNT(FIRST_NAME) AS TOP_NAME_FREQUENCY //2nd chunk starts
FROM
(SELECT FIRST_NAME, COUNT(FIRST_NAME) AS NUM_NAMES
FROM USERS_FAKE U
GROUP BY FIRST_NAME
ORDER BY NUM_NAMES DESC));
但是,此查询在语法上不正确。当我尝试运行此查询时,出现错误消息:
WHERE COUNT(FIRST_NAME) AS MOST_FREQUENCY =
*
ERROR at line 3:
ORA-00934: group function is not allowed here
然后我的问题是,如何才能以SQL可接受的方式组合这些查询?
您不能在COUNT()
子句中使用WHERE
。只有选择了所有行,聚合才会完成,因此只能在SELECT
列表和HAVING
子句中使用它们。
也不需要您全部使用DISTINCT
。每当您分组时,您都会得到不同的结果。要获得最高计数,请使用ORDER BY num_names DESC LIMIT 1
。
SELECT first_name, COUNT(*) AS most_frequent
FROM USERS_FAKE
HAVING most_frequent = (
SELECT COUNT(*) AS num_names
FROM USERS_FAKE
GROUP BY first_name
ORDER BY num_names DESC
LIMIT 1
)