[英]SQLITE select by group and limit results for each group
I have the following SQLITE table:我有以下 SQLITE 表:
COL1 COL1 | COL2 COL2 | COL3 COL3 |
---|---|---|
tit1山雀1 | cat1猫1 | time1时间1 |
tit2山雀2 | cat3三类 | time2时间2 |
tit3山雀3 | cat1猫1 | time3时间3 |
tit4山雀4 | cat1猫1 | time4时间4 |
tit5山雀5 | cat3三类 | time5时间5 |
tit6 tit6 | cat2猫2 | time6时间6 |
tit7山雀7 | cat1猫1 | time7时间7 |
I want to SELECT all rows grouped by COL2, WHERE COL2 == cat1 or cat2, but LIMIT the results to max 2 rows for each group and ORDER the results by COL3 DESC.我想 SELECT 所有按 COL2、WHERE COL2 == cat1 或 cat2 分组的行,但将每个组的结果限制为最多 2 行,并按 COL3 DESC 对结果进行排序。
So, for instance, in this case I want to get only:因此,例如,在这种情况下,我只想得到:
COL1 COL1 | COL2 COL2 | COL3 COL3 |
---|---|---|
tit7山雀7 | cat1猫1 | time7时间7 |
tit4山雀4 | cat1猫1 | time4时间4 |
tit6 tit6 | cat2猫2 | time6时间6 |
Is it possible to obtain this with (possibly) one or max 2 queries?是否可以通过(可能)一个或最多 2 个查询来获得此信息?
So far I tried this, but it doesn't work as expected:到目前为止,我尝试了这个,但它没有按预期工作:
SELECT * FROM "tablename" WHERE "COL2" = "cat1" OR "COL2" = "cat2" GROUP BY "COL2" ORDER BY "COL3" DESC LIMIT 2
Thank you for your help谢谢您的帮助
Filter the table and use ROW_NUMBER() window function:过滤表并使用 ROW_NUMBER() window function:
SELECT COL1, COL2, COL3
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY COL2 ORDER BY COL3 DESC) rn
FROM tablename
)
WHERE rn <= 2
ORDER BY COL2, COL3 DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.