對於此特定查詢,您需要每個大洲的最大和次大值。我將與窗口函數處理這個:
select w.continent,
max(case when seqnum = 1 then w.name end) as name
from (select w.*,
row_number() over (partition by continent order by population desc) as seqnum
from world w
) w
where seqnum in (1, 2)
group by continent
having max(case when seqnum = 1 then population end) > 3*max(case when seqnum = 2 then population end)
好吧,我承認,這可能是一個有點先進的,考慮到問題的根源。
所以,這裏是一個方法,你可以把它用做連接,而不是相關子查詢:
我認爲下面就你的邏輯:
select w.name, w.continent
from world w join
(SELECT w.continent, maxpopulation,
max(case when population <> maxpopulation then population end) as secondmax
FROM world w join
(select continent, max(population) as maxpopulation
from world
group by continent
) c
on w.continent = c.continent
group by w.continent, maxpopulation
) wc
on w.continent = wc.continent and w.population = maxpopulation
where population >= 3*secondmax
因此,答案是「是的,你可以做這個沒有相關的子查詢。「在大多數情況下,您可以使用連接和分組來重寫相關的子查詢。
我相信你可能誤解了任務。你是否遵循了我提供的SQLZOO鏈接? – 2013-02-21 17:45:41
作爲一個說明。 。 。自評論以來,我已經完全重寫了答案。 – 2013-02-21 19:23:55
非常感謝。很有意思。 您的第一個查詢按預期工作。然而,甲骨文抱怨第二個。我無法找到解決辦法。 當你有一刻可以重新訪問它嗎? – 2013-02-21 21:25:56