-1

我正在尝试使用 sqlite 在一张表中获得每个国家/地区最赚钱的用户 ID。我不确定在哪里使用 LIMIT 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
4

3 回答 3

0

由于 SQLite 不支持windows 功能,所以你可以写一个子查询是 a seqnumby Country,然后得到 top 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:https ://www.db-fiddle.com/f/tmNhRLGG2oKqCKXJEDsjfe/0

于 2018-06-14T07:58:01.320 回答
0

LIMIT不会有用,因为它适用于整个结果集。

我会像这样创建一个辅助列“CountryRank”:

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;
于 2018-06-14T08:01:55.393 回答
0

一种非常简单的方法是:

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()

select t.*
from t
where t.profit >= coalesce((select t2.profit
                            from t t2
                            where t2.country = t.country
                            order by t2.profit desc
                            limit 1 offset 2
                           ), t.profit
                          );
于 2018-06-14T11:46:24.160 回答