如何根据sqlite中的另一列为每个组选择前3名?

如何根据sqlite中的另一列为每个组选择前3名?,sql,sqlite,Sql,Sqlite,我正在尝试使用sqlite在一个表中获得每个国家最赚钱的三个用户ID。我不确定在哪里使用极限3。 这是我的表格: Country | UserID | Profit US 1 100 US 12 98 US 13 10 US 5 8 US 2 5 IR 9 95 IR 3 90 IR

我正在尝试使用sqlite在一个表中获得每个国家最赚钱的三个用户ID。我不确定在哪里使用极限3。 这是我的表格:

Country | UserID | Profit
US        1         100
US        12        98
US        13        10
US        5         8
US        2         5
IR        9         95
IR        3         90
IR        8         70
IR        4         56
IR        15        40
结果应该如下所示:

Country | UserID | Profit
US        1         100
US        12        98
US        13        10
IR        9         95
IR        3         90
IR        8         70
SELECT *, (SELECT COUNT() FROM Data AS d WHERE d.Country=Data.Country AND d.Profit>Data.Country)+1 AS CountryRank
FROM Data;

由于SQLite不支持windows函数,所以您可以按国家编写一个子查询,然后获得前3名

您可以尝试此查询

select t.Country,t.UserID,t.Profit
from(
  select t.*,
               (select count(*)
                from T t2
                where t2.Country = t.Country and t2.Profit >= t.Profit
               ) as seqnum
   from T t
)t
where t.seqnum <=3
sqlfiddle:

限制将不起作用,因为它适用于整个结果集

我会创建一个辅助列CountryRank,如下所示:

Country | UserID | Profit
US        1         100
US        12        98
US        13        10
IR        9         95
IR        3         90
IR        8         70
SELECT *, (SELECT COUNT() FROM Data AS d WHERE d.Country=Data.Country AND d.Profit>Data.Country)+1 AS CountryRank
FROM Data;
以及对该结果的查询:

SELECT Country, UserID, Profit
FROM (
    SELECT *, (SELECT COUNT() FROM Data AS d WHERE d.Country=Data.Country AND d.Profit>Data.Profit)+1 AS CountryRank FROM Data)
WHERE CountryRank<=3
ORDER BY Country, CountryRank;

一个非常简单的方法是:

select t.*
from t
where t.profit >= (select t2.profit
                   from t t2
                   where t2.country = t.country
                   order by t2.profit desc
                   limit 1 offset 2
                  );
这假设每个国家至少有三项记录。您可以使用coalesce解决此问题: