如何限制总计列sql中的每一行?

时间:2019-03-18 14:00:33

标签: sql database sqlite subquery

我有一列这样的

total  name   gender 
2      Mike   male
2      Dion   male 
2.     Shinta female
2      Sarah  female
10     Pio    male
10     Olive  female
10     Steve  male
80     Yuri   female
80     Kio    male. 
80     Doni   male
80     Dora   female
80     Nobi   male. 
80     Hiou   male

如何将每个总数限制为仅2个人? 我从创建的View and Join中获得了该表,并获得了该表,但是如果我限制了,它仅限制了顶部的第一行,而不是每个总计 我真的很想让每个人有2个人共2个人,总共10个人有2个人,而80个人有2个人, 那有可能吗?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用row_number()

select * from
(
select *, row_number() over(partition by total order by null) as rn
from tablename
)A where rn<=2

答案 1 :(得分:0)

通常会使用窗口函数:

select t.*
from (select t.*, row_number() over (partition by total order by total) as seqnum
      from tempview t  -- or whatever your logic is here
     ) t
where seqnum <= 2;

当然,窗口功能仅在最新版本的SQLite中可用。

在旧版本的SQLite中,这很痛苦,但这应该可以工作:

select t.*
from tempview t
where t.name in (select t2.name
                 from tempview t2
                 where t2.total = t.total
                 limit 2
                );

这假定对于给定的total,名称不会重复。