SQLite:为n个用户选择前x个值

时间:2019-03-06 09:11:25

标签: sqlite

我有一个看起来像示例的Sqlite DB表(测试):

User Score

用户看起来像User1,User2 ... User 20

分数是整数。

示例:

User1 204
User2 5555
User6 102
etc.

如何为按分数排序的每个现有用户选择3个最高值?例如:

User1 4344
User1 4000
User1 2330
User2 2300
User2 1000
User2 300
User3 555
User3 100
User3 10
User4 2033
...

这仅使我成为所有用户中的前3名。

  SELECT user, score FROM test ORDER BY score DESC limit 3

这给了我所有用户,但只有一个最高价值。

  SELECT user, score FROM test GROUP BY user ORDER BY score DESC

到目前为止,我发现的唯一的解决方案是将所有用户添加到列表中并使用循环(我使用Python)。每次分析一个用户。 但是我很好奇是否有可能在没有循环的情况下仅通过Sqlite做到这一点?

2 个答案:

答案 0 :(得分:0)

窗口函数是您的朋友(需要3.25或更高版本):

SELECT user, score
FROM (SELECT user, score,
             row_number() OVER (PARTITION BY user ORDER BY score DESC) AS rn
       FROM test)
WHERE rn <= 3
ORDER BY user, score DESC;

答案 1 :(得分:-1)

您需要创建另一个表来存储输出结果,在我的示例中,我将其称为 outputresult(user,score)

Declare     @duser nvarchar(30)
Declare     @duser2 nvarchar(30)
Declare     @dscore int

DECLARE cur1 CURSOR FOR
select distinct [user] from TOP3s



OPEN cur1

FETCH NEXT FROM cur1 INTO @duser

WHILE @@Fetch_Status = 0 

BEGIN

Declare cur2 Cursor FOR
select top (3) [user], score from TOP3s where [user] = @duser order by [user], score desc
OPEN cur2

fetch next from cur2 into @duser2, @dscore

WHILE @@Fetch_Status = 0 

begin

insert into outputresult values(@duser2, @dscore)

fetch next from cur2 into @duser2, @dscore

end

close cur2
deallocate cur2


FETCH NEXT FROM cur1 INTO @duser

end

close cur1

Deallocate cur1


--you can run this query to check the output:
select * from outputresult