SQL 每个项目组的前 N 个和每个用户的前 M 个

问题描述 投票:0回答:2

样本数据:

user_id item_type item_count
11 A 10
11 A 9
11 A 2
11 4
11 1
11 C 2
12 A 2
12 4
12 1
12 D 1

期望的输出:

user_id item_type item_count
11 A 10
11 4
11 C 2
12 A 2
12 4
12 D 1

对于每个用户,我想要他们拥有的每个项目类型中按项目计数排在首位的项目。因此,对于用户 11,他们应该获得项目 A 的最高记录、项目 B 的最高记录和 c 的最高记录。我有点卡住了。我认为这应该是一个双重排名问题,但我能找到的大多数例子都是为顶级用户/项目选择,无论项目类型如何,但我想要每个用户每个项目类型的顶级项目。

select * from (
    select user_id, 
           item_type,
           item_count, 
           row_number() over (partition by user order by item_count desc) as item_rank 
    from table) ranks
where item_rank <= 2;

这只是获取每个用户的热门项目,但我想要每个用户每个项目类型的热门项目。

sql apache-spark-sql greatest-n-per-group ranking
2个回答
0
投票

你想在这里按用户项目分区:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY user_id, item_type
                                   ORDER BY item_count DESC) rnk
    FROM yourTable t
)

SELECT user_id, item_type, item_count
FROM cte
WHERE rn <= 2
ORDER BY user_id, item_type;

0
投票

这可以在不使用 Window 函数的情况下实现。

您可以按

user_id
item_type
分组,然后在
Max
上获得
item_count

DECLARE @table TABLE
(
    user_id int,
    item_type char,
    item_count int
)

insert into @table
values
(11,    'A',    10),
(11,    'A',    9 ),
(11,    'A',    2 ),
(11,    'B',    4 ),
(11,    'B',    1 ),
(11,    'C',    2 ),
(12,    'A',    2 ),
(12,    'B',    4 ),
(12,    'B',    1 ),
(12,    'D',    1 )

select * from @table


select
    user_id, item_type, Max(item_count)
from @table
    group by user_id, item_type
order by user_id
© www.soinside.com 2019 - 2024. All rights reserved.