请让我知道以下命令有什么问题
mysql> select max(count(*)) from emp1 group by name;
ERROR 1111 (HY000): Invalid use of group function
请让我知道以下命令有什么问题
mysql> select max(count(*)) from emp1 group by name;
ERROR 1111 (HY000): Invalid use of group function
尝试:
SELECT NAME, COUNT(*) as c FROM table GROUP BY name ORDER BY c DESC LIMIT 1
从提供的代码中,我了解到您希望选择最多数量的同名员工。
您的查询的问题是您试图在单个范围内应用多个级别的聚合。
尝试这个:
SELECT MAX(Total) FROM (SELECT COUNT(*) AS Total FROM emp1 GROUP BY name) AS Results
...或这个:
SELECT COUNT(name) FROM emp1 GROUP BY name ORDER BY COUNT(name) DESC LIMIT 1
两个查询都返回相同的结果,但它们的实现不同。
使用对您来说最快的或您喜欢的任何一个。
You are asking "what is wrong with your statement". This is your statement:
select max(count(*))
from emp1
group by name;
I understand what you mean. But a SQL Compiler does not. The reason is simple. A given select
can have only one group by
clause. And your query is asking for two of them. The first is the group by
name. The second is an aggregation on all those results.
The proper way to write your query (as you seem to intend) is using a subquery:
select max(cnt)
from (select count(*) as cnt
from emp1
group by name
) t
This is a perfectly reasonable solution that only uses standard SQL. Other answers have proposed the solution using the limit
clause, which may be a bit more efficient.
我要以下(假设我正确理解你想要什么):
select c from
(
select count(*) as c, name from emp1 group by name
) tmp
order by c desc limit 1
这将按名称从所有计数中选择最大的计数。例如,如果您的表包含
Name
-----------------------
Test
Test
Hello
World
World
World
内部选择将使用此数据创建一个“表”
c Name
----------------------
2 Test
1 Hello
3 World
外部选择将按c
降序排序并选择第一个条目,即3
.
这可以缩短为
select count(*) c from emp1 group by name order by c desc limit 1
您必须选择name
按它进行分组,然后将max()
其结果用作子查询:
select max(count)
from (
select
name,
count(*) as count
from emp1
group by name) x
我已经格式化了查询,所以你可以看到发生了什么,而不是像你展示的那样把它全部放在一行上。顺便说一句,fnf 处的“x”是子查询的必需别名。
SELECT MAX(name_count)
FROM
(
SELECT name
,count(*) as name_count
FROM emp1
GROUP BY
name
)
如果数据碰巧多次出现最大值,则LIMIT 1将不会回答问题。为了说明这一点,我使用MySQL中的WOLRD数据库示例来回答这个问题。
Q) 返回语言数量最多的国家/地区列表。
五个国家适合拥有相同数量的语言,即12种
首先,我们需要创建一个VIEW来保存最大值(在本例中为 12)
CREATE VIEW abc AS SELECT count(countrycode) AS total FROM
countrylanguage GROUP BY countrycode
ORDER BY COUNT(countrycode) DESC limit 1;
然后在下面的SELECT语句中使用视图:
SELECT `name`, COUNT(country.`name`) FROM country JOIN
countrylanguage ON country.`code` = countrylanguage.countrycode
GROUP BY country.`name`
HAVING COUNT(country.`name`) = (SELECT total FROM abc) ;
***Example: 1***
SELECT *
FROM customer
WHERE customer.ID IN
(SELECT customer_id
FROM (SELECT customer_id, MAX(cust_count)
FROM (SELECT customer_id,
COUNT(customer_id)
AS cust_count
FROM `order`
GROUP BY customer_id) AS cust_count_tbl) AS cust_tbl);
***Example -2***
SELECT *
FROM customer
LEFT JOIN
(SELECT customer_id, COUNT(customer_id) AS cc
FROM `order`
GROUP BY customer_id
ORDER BY cc DESC
LIMIT 1) AS kk
ON customer.ID = kk.customer_id
WHERE kk.customer_id = customer.ID;