gpt4 book ai didi

sql - Sqlite 中每个类别的前 n 个计数

转载 作者:行者123 更新时间:2023-12-03 17:57:04 24 4
gpt4 key购买 nike

我有一张看起来像的 table :

user    books
a aa
a ab
a ab
a ac
a ac
a ac
b aa
b aa
b aa
b ac
c aa
c aa
c ab
c ab
c ab

我想要一个聚合字段,其中包含每个用户的唯一书籍计数 - 我想按降序显示其中的前 2 个,这意味着:
user    book    count  
a ac 3
a ab 2
b aa 3
b ac 1
c ab 3
c aa 2

我正在使用sqlite。

在 postgres 中,我会让你过度分区,但我认为 sqllite 中没有等价物。
有什么建议吗?

最佳答案

这对 SQLite 来说是一个真正的痛苦,因为它既没有变量也没有窗口函数。一种方法是相关子查询:

with ub as (
select user, book, count(*) as cnt
from t
group by user, book
)
select ub.*
from ub
where ub.book in (select ub2.book
from ub ub2
where ub2.user = ub.user
order by cnt desc
limit 2
);

注意:如果有平局,则任意选择其中两个。

关于sql - Sqlite 中每个类别的前 n 个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042276/

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