Sqlite 中每个类别的前 n 个计数
Top n Count per category in Sqlite
我有一个 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 中是一个真正的痛苦,因为它既没有变量也没有 window 函数。一种方法是相关子查询:
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
);
注意:如果有平局,则随机选择其中两个。
试试这个:
Select user, book, count(*) cnt
From t a
Where book in (
Select book
From t b
Where a.user = b.user
Group by book
Order by count(*) desc
Limit 2
)
Group by user, book;
我有一个 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 中是一个真正的痛苦,因为它既没有变量也没有 window 函数。一种方法是相关子查询:
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
);
注意:如果有平局,则随机选择其中两个。
试试这个:
Select user, book, count(*) cnt
From t a
Where book in (
Select book
From t b
Where a.user = b.user
Group by book
Order by count(*) desc
Limit 2
)
Group by user, book;