gpt4 book ai didi

sql - 选择总和最大

转载 作者:行者123 更新时间:2023-12-03 19:13:15 25 4
gpt4 key购买 nike

我有一些这样的表的结果(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

最佳答案

首先说明:


您必须使用显式联接,而不是隐式联接。
另外,您必须将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

关于sql - 选择总和最大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55620204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com