让我们说,我有下表:
| Name | Voters
| George | 10
| Barack | 20
| Barack | 50
| Barack | 40
| Donald | 30
| Bill | 20
| George | 10
| Bill | 30
| Bill | 15
| Bill | 10
我想得到每个姓名(或更少)的2个最大选民人数的总和
| Name | Sum2BiggestVoters
| George | 20 (10 + 10)
| Donald | 30 (30)
| Bill | 20 (30 + 20; 10 and 15 are not considered not part of the 2 biggest numbers of voters for Bill)
| Barack | 90 (50 + 40; 20 is not considered here for the same reason as above)
看起来有点像这篇文章:How to get summation with count larger than certain amount,除了我使用的SQLite缺少row_number() over
功能以及partition by
。
有什么想法吗?
答案 0 :(得分:1)
这是SQLite的一个难点,因为它不支持变量,也不支持窗口函数。假设您与给定的name
没有关系,您可以这样做:
select t.name, sum(t.voters)
from t
where t.voters in (select t2.voters
from t t2
where t.name = t2.name
order by t2.voters desc
limit 2
)
group by t.name;