SQLZOO练习题(1)
sqlzoo上较难的一些sql查询练习题及其解题思路。
题目:
Put the continents right…
- Oceania becomes Australasia
- Countries in Eurasia and Turkey go to Europe/Asia
- Caribbean islands starting with ‘B’ go to North America, other Caribbean islands go to South America
Show the name, the original continent and the new continent of all countries.
答案:
select name, continent, case
when continent='oceania' then 'Australasia'
when continent in ('eurasia', 'turkey') then 'Europe/Asia'
when continent='caribbean' then case
when name like 'B%'
then 'North America'
else 'South America'
end
else continent
end
from world
order by name asc
思路:
主要涉及case
函数的用法。
当满足condition1时,返回value1,满足condition2,返回value2,都不满足返回def_value。
该题解法在于使用一个case函数的嵌套。让以B开头的加勒比岛国属于北美,非B开头的属于南美。在父case when continent = ‘caribbean’ then后应该填入需要返回的value。但是这里我们需要做一个判断,所以再嵌套一个case,判断when name like 'B%'时返回北美,否则返回南美。这样经过判断后的北美和南美就作为子case返回的value传递给父case,填入到then后面的返回值中。
希望本文对你有所帮助。