使用sql使用max和count

时间:2018-04-20 17:45:51

标签: mysql sql count

找到拥有最多客户的区域(显示区域名称和 MAX(no_of_customers)

select c.Region,max(total) 
from (select c.Region,count(c.Cust_id) as total
    from cust_dimen c
    group by Region) as total;

但显示错误

SELECT region
FROM cust_dimen
GROUP BY region
HAVING COUNT(cust_id)=
    (SELECT MAX(t) FROM
        (SELECT region,COUNT(cust_id) AS t,count(Cust_id) as total
         FROM cust_dimen
         GROUP BY region) t1);

它显示区域,但我甚至需要计数

3 个答案:

答案 0 :(得分:1)

只需使用order bylimit

select c.Region, count(*) as total
from cust_dimen c
group by Region
order by total desc
limit 1;

答案 1 :(得分:0)

SELECT region, COUNT(DISTINCT cust_id) AS cnt
FROM cust_dimen
GROUP BY region
HAVING COUNT(DISTINCT cust_id) =
(SELECT MAX(cnt)
 FROM
 (SELECT region, COUNT(DISTINCT cust_id) AS cnt
  FROM cust_dimen
  GROUP BY region) sub)

你很接近 - 只需在你的select语句中添加计数。

答案 2 :(得分:0)

Intentalo asi: SELECT区域,COUNT(cust_id)编号FROM cust_dimenGROUP BY区域ORDER BY编号DESC LIMIT 1

相关问题