sql - 使用 SQL 从每个类别中选择两个元素
问题描述
考虑下表
id | fruit | score
---+-------+------
1 | pear | 9
2 | plum | 5
3 | plum | 7
4 | apple | 4
5 | plum | 2
6 | pear | 3
我需要一个 SQL(POSTGRES 方言)查询,它选择得分最低的苹果和李子,每个类别两个。结果将是
id | fruit | score
---+-------+------
4 | apple | 4
5 | plum | 2
2 | plum | 5
我从
SELECT id, fruit, score
FROM fruit_score
WHERE fruit IN ('apple', 'plum')
ORDER BY score
我怎么吃LIMIT
水果?
解决方案
row_number()
如果要保证每行有两行,则可以使用fruit
:
select fs.*
from (select fs.*, row_number() over (partition by fruit order by score asc) as seqnum
from fruit_score fs
where fruit IN ('apple', 'plum')
) fs
where seqnum <= 2;
推荐阅读
- css - iPad 上的 Twitter 提要 - 页面在滚动和灰色边框上移动
- c++ - 如何在存储在 std::vector 中的非平凡可复制/可破坏类型上调用析构函数
? - r - 创建合成数据 - 平衡数据集
- css - ASP.NET MVC - 为什么 CSS 在视图中不能正常工作?按钮看起来甚至完全不同
- powershell - SharePoint Online - 移动文档库内容(文件和文件夹)
- javascript - 如何用 JavaScript 中的正则表达式捕获组替换整个字符串?
- java - int[] 如何被接受为通用类型参数而不是 int?
- google-apps-script - 为什么某些由带有表单提交触发器的 Google Apps 脚本发送的电子邮件会发送两次?
- build - 嵌入式领域中的“构建系统”是什么?
- c# - 尝试在 C# 中对具有多个线程的数组进行排序时出现问题