简化 sql

Simplify in sql

我有一些任务需要 sql 完成。 下面是我目前使用的功能。

(SELECT ProductName, sum(Quantity*Price) Revenue, Country
  FROM products p
    JOIN orderdetails d
      ON p.ProductID = d.ProductID
      JOIN orders o
        ON o.OrderID = d.OrderID
        JOIN customers c
          ON c.CustomerID = o.CustomerID
    WHERE Country = 
    (
      SELECT DISTINCT Country
        FROM customers
          LIMIT 1
    )
      GROUP BY ProductName
        ORDER BY Revenue DESC
          LIMIT 1)
UNION
(SELECT ProductName, sum(Quantity*Price) Revenue, Country
  FROM products p
    JOIN orderdetails d
      ON p.ProductID = d.ProductID
      JOIN orders o
        ON o.OrderID = d.OrderID
        JOIN customers c
          ON c.CustomerID = o.CustomerID
    WHERE Country = 
    (
      SELECT DISTINCT Country
        FROM customers
          LIMIT 1,1
    )
      GROUP BY ProductName
        ORDER BY Revenue DESC
          LIMIT 1)        
UNION
(SELECT ProductName, sum(Quantity*Price) Revenue, Country
  FROM products p
    JOIN orderdetails d
      ON p.ProductID = d.ProductID
      JOIN orders o
        ON o.OrderID = d.OrderID
        JOIN customers c
          ON c.CustomerID = o.CustomerID
    WHERE Country = 
    (
      SELECT DISTINCT Country
        FROM customers
          LIMIT 2,1
    )
      GROUP BY ProductName
        ORDER BY Revenue DESC
          LIMIT 1)

我的任务是“根据每个国家/地区的收入找到最畅销的产品!

我想要的结果如下:

ProductName Revenue Country
Tofu 279 Argentina
Côte de Blaye 18445 Austria

你可以从这里访问我使用的数据 link RawDatabase

我用的样本数据是这样的

ProdName Country Revenue
coco Argentina 120
bread Austria 10000
crunch Austria 13265
Cote de Blaye Austria 18445
milk Argentina 254
Tofu Argentina 279

根据这些数据,我想 select 仅根据收入为每个国家/地区提供最好的产品。在数据中有 21 个国家。我应该怎么做才能得到下面的结果

ProductName Revenue Country
Tofu 279 Argentina
Côte de Blaye 18445 Austria

在我看来,唯一的方法就是按每个国家/地区过滤数据,然后获得最好的产品,然后像我在上面给出的代码一样合并所有这些产品。请问有没有别的办法

使用 row_number window 函数或与国家/地区 maxrevenue

进行比较
DROP TABLe if exists t;
create table t
(ProdName varchar(20),  Country varchar(20),    Revenue int);
insert into t values
('coco' ,'Argentina'    ,120),
('bread'    ,'Austria'     ,10000),
('crunch','Austria'    ,13265),
('Cote de Blaye'    ,'Austria', 18445),
('milk' ,'Argentina'    ,254),
('Tofu' ,'Argentina'    ,279);

select * 
from
(
select prodname,country,revenue, 
         row_number() over(partition by country order by revenue desc) rn
from t
) s
where rn = 1;

select * 
from t
join (select t.country,max(t.revenue) maxrevenue from t group by t.country) t1
        on t1.country = t.country and t1.maxrevenue = t.revenue;

+---------------+-----------+---------+----+
| prodname      | country   | revenue | rn |
+---------------+-----------+---------+----+
| Tofu          | Argentina |     279 |  1 |
| Cote de Blaye | Austria   |   18445 |  1 |
+---------------+-----------+---------+----+
2 rows in set (0.001 sec)