2017-06-24 20 views
0

は、私は以下のこのテーブルを持っている、のは、言ってみましょう:各グループ(グループ別)の2つの最大値に基づいて合計を計算する方法は?

| 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、私はpartition byと同様にrow_number() overの機能がないSQLiteを使用しています。

答えて

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; 
+0

の作品は、最初のwhere句の最後にタイプミスを除いて、あなたはセミコロンを残しました「;」同じ「外側」の節でROWIDを活用する方が良いと思います。 – Ehouarn

関連する問題