任务:
查找最大客户所在的国家/地区。
查询
SELECT country,
count(*)
FROM customers
GROUP BY country
HAVING count(*) =
(SELECT max(max_sal)
FROM
(SELECT count(*) max_sal
FROM customers
GROUP BY country)) ;
结果:
结果是正确的,但我认为编写查询很难。
问题:有没有简单的方法可以重写此查询。
答案 0 :(得分:2)
我可能会遗漏一些东西,但它可以像这样简单:
SELECT *
FROM ( SELECT country, COUNT (*) max_sal
FROM customers
GROUP BY country
ORDER BY COUNT (*) DESC)
WHERE ROWNUM <= 1;
答案 1 :(得分:1)
您可以使用WITH
子句:
WITH
c AS (
SELECT country, Count(1) n
FROM customers
GROUP BY country)
SELECT country, n
FROM c
WHERE n = (SELECT Max(n) FROM c)
答案 2 :(得分:1)
你可以使用解析函数over()你得到每行结果的max(avg,min等)结果然后在compare count(1)和max(count(1))
这里是例子:
SELECT country, cnt, max_cnt
FROM (SELECT country, COUNT(1) AS cnt, MAX(COUNT(1)) over() max_cnt
FROM customers
GROUP BY country)
WHERE cnt = max_cnt
答案 3 :(得分:1)
SELECT Country, MAX(N) FROM (
SELECT Country, COUNT(*) as N FROM CUSTOMERS GROUP BY Country
);