【问题标题】:How to compute a sum based on the 2 biggest values for each group (group by)?如何根据每个组(分组依据)的 2 个最大值计算总和?
【发布时间】:2017-06-24 14:45:30
【问题描述】:

比方说,我有下面这张表:

| 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

有什么想法吗?

【问题讨论】:

    标签: sql sqlite group-by


    【解决方案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;
    

    【讨论】:

    • 就像一个魅力,除了第一个 where 子句末尾的错字,你留下了一个分号“;”而且我认为最好在同一个“外部”where子句中利用rowid。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多