mysql - SQL 中字段对的首次出现
问题描述
我的表如下所示:
+------------+---------------+--------+
| 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;
推荐阅读
- javascript - 我想计算 math.min 以从输出中排除零?
- react-admin - 如何让反应管理员数据提供者接受 createMany?
- php - 如何仅让一个用户访问管理面板 NOVA?
- css - 在角度应用程序上缓存字体的正确方法是什么
- java - 可能的致命错误:未找到物理字体
- c# - ASW 代码构建报告是否支持 .Net 代码覆盖率工具?
- linux - Gtk-rs 在异步数据获取上崩溃 gnomne 会话并将其分配给按钮单击事件上的标签
- hangout - 是否可以将机器人添加到环聊(不是 Google 聊天)?
- java - 使用递归时无法执行二叉搜索树遍历
- echo - 如何撤消附加回显命令