选择最大总和

时间:2019-04-10 19:43:13

标签: sql sqlite sum max

我从类似的表格中得到了结果(有700行)

country         province       purchase_power 
Angola          Cuanza Sul          10
Angola          Huambo              2
Angola          Namibe              2
Angola          Uige                12
Argentina       Buenos Aires        15
Argentina       Catamarca           3
Argentina       Corrientes          1
Argentina       Jujuy               13
Argentina       La Rioja            17
Argentina       Mendoza             1
Argentina       Misiones            1
Argentina       Neuquen             2
Argentina       San Juan            10
Argentina       San Luis            4
Argentina       Santa Cruz          1

我通过使用此查询得到了

select  c.name as country,p.name as province,sum(qty) as purchase_power
from province p,purchases,country c
where P.rowid = Purchases.province and qty>0 and c.code=p.country and product=0  
group by p.name 

我只希望每个国家的购买力最高的省

应该考虑表演

ex output 
country         province       purchase_power 
Angola          Uige                12
Argentina       La Rioja            17

1 个答案:

答案 0 :(得分:1)

第一笔记:

  • 您必须使用显式联接,而不是隐式联接。
  • 另外,您必须将c.name添加到group by
  • 尽管SQLite允许选择group by子句中未使用的列,但是如果您不希望出现意外,则必须遵循标准SQL。

现在,由于性能是一个问题,因此您可以对查询使用CTE,并且只执行一次即可使用其结果:

with cte as (
  select 
    c.name as country,
    p.name as province,
    sum(t.qty) as purchase_power
  from province p 
  inner join purchases t on p.rowid = t.province
  inner join country c on c.code = p.country 
  where t.qty > 0 and t.product=0  
  group by c.name, p.name
)
select cte.* from cte 
inner join (
  select country, max(purchase_power) purchase_power
  from cte
  group by country
) t on t.country = cte.country and t.purchase_power = cte.purchase_power