查询简化 Oracle Northwind

Query simplification Oracle Northwind

任务:

查找最多客户所属的国家/地区。

查询

SELECT country,
       count(*)
FROM customers
GROUP BY country
HAVING count(*) =
  (SELECT max(max_sal)
   FROM
     (SELECT count(*) max_sal
      FROM customers
      GROUP BY country)) ;

结果:

结果是正确的,但我认为编写查询的方法很困难

问题:有什么简单的方法可以重写这个查询吗

您可以使用 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)

我可能遗漏了一些东西,但它可以像这样简单:

SELECT *
  FROM (  SELECT country, COUNT (*) max_sal
            FROM customers
        GROUP BY country
        ORDER BY COUNT (*) DESC)
 WHERE ROWNUM <= 1;

你可以使用分析函数 over(),你可以在结果的每一行得到最大值(平均值、最小值等),然后在其中比较 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
SELECT Country, MAX(N) FROM (
    SELECT Country, COUNT(*) as N FROM CUSTOMERS GROUP BY Country
);