我正在使用可以在这里查询http://www.semwebtech.org/sqlfrontend/的mondial数据库
我试图获得在每个大陆上实践最多的3种宗教,我已经想出了这个:
select religion.name, sum(religion.percentage) as total, continent
from religion join encompasses on religion.country = encompasses.country
group by name, continent order by continent, total DESC
这给了我一个列表,列出了每个大陆按其受欢迎程度排序的每个宗教,但我如何得到每个大陆的前3个结果?
我已经查找了光标,但我没有看到如何将它们应用到我的案例中,看起来有一个简单的答案
我会使用窗口函数:
select rc.*
from (select r.name, sum(r.percentage) as total, e.continent,
row_number() over (partition by e.continent order by sum(r.percentage) as total desc) as seqnum
from religion r join
encompasses e
on r.country = e.country
group by r.name, e.continent
) rc
where seqnum <= 3;
在解释了如何修改查询以回答问题之后,现在让我指出您的查询是错误的。人口百分比的总和与总人数不同。例如,我认为不丹非常接近100%的佛教徒(佛教是国教)。但是印度有更多的佛教徒(根据一个消息来源,约有0.7%的佛教徒)。