一尘不染

postgres:获取每个组中前n个出现的值

sql

我有一个简单的表,像这样:

user    letter
--------------
1       A
1       A
1       B
1       B
1       B
1       C

2       A
2       B
2       B
2       C
2       C
2       C

我想获得每个用户出现的前2个“字母”,

user    letter  rank(within user group)
--------------------
1       B       1
1       A       2

2       C       1
2       B       2

甚至更好:崩溃成列

user    1st-most-occurrence  2nd-most-occurrence
1       B                   A
2       C                   B

我怎样才能在postgres中做到这一点?


阅读 196

收藏
2021-03-08

共1个答案

一尘不染

with cte as (
    select 
        t.user_id, t.letter,
        row_number() over(partition by t.user_id order by count(*) desc) as row_num
    from Table1 as t
    group by t.user_id, t.letter
)
select
    c.user_id,
    max(case when c.row_num = 1 then c.letter end) as "1st-most-occurance",
    max(case when c.row_num = 2 then c.letter end) as "2st-most-occurance"
from cte as c
where c.row_num <= 2
group by c.user_id

= > SQL小提琴演示

2021-03-08