gpt4 book ai didi

mysql - SQL 中字段对的首次出现

转载 作者:行者123 更新时间:2023-11-29 07:17:52 25 4
gpt4 key购买 nike

我的表格是这样的:

+------------+---------------+--------+
| City | Category Name | Orders |
+------------+---------------+--------+
| London | Components | 29 |
| Woolston | Bikes | 16 |
| Union City | Clothing | 13 |
| London | Bikes | 13 |
| Union City | Bikes | 11 |
| Union City | Components | 11 |
| Woolston | Clothing | 11 |
| Woolston | Components | 8 |
| Woolston | Accessories | 8 |
| Union City | Accessories | 8 |
| London | Clothing | 4 |
| London | Accessories | 1 |
+------------+---------------+--------+

目标是获取每个城市及其最受欢迎的类别,因此:

+------------+---------------+
| City | Category Name |
+------------+---------------+
| London | Components |
| Woolston | Bikes |
| Union City | Clothing |
+------------+---------------+

在这种情况下,我需要选择第一个表中每个城市的第一次出现及其类别。

我试过使用标准:

SELECT City, Max(Orders) 
FROM Table
GROUP BY City

然而,一旦您尝试将类别名称添加到组合中,这就会开始成为问题,而且我也不希望新表中的 Orders 字段。

有没有办法很好地做到这一点?

最佳答案

您可以使用窗口函数或相关子查询:

select t.*
from t
where t.orders = (select max(t2.orders) from t t2 where t2.city = t.city);

作为窗口函数:

select t.*
from (select t.*, row_number() over (partition by city order by orders desc) as seqnum
from t
) t
where seqnum = 1;

关于mysql - SQL 中字段对的首次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58221912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com