简体   繁体   English

具有多个条件和排序的案例陈述

[英]Case statement with multiple conditions and sort

I need to pull from 'world' table and add a CASE WHEN statement to make it so continent name 'Caribbean' changes to 'North America' when country 'name' is LIKE 'B%', but when name is not LIKE 'B%' then continent will='South America'. 我需要从“世界”表中提取并添加CASE WHEN语句,以使当国家/地区的名称为“ B%”时,洲名称“加勒比海”更改为“北美”,但当名称与“ B”不同时, %',那么大陆将='南美'。 Also needs to be in ASC order by name. 还需要按名称按ASC顺序排列。

I know all the commands to do this but can't seem to get them in the right order or syntax. 我知道所有执行此操作的命令,但似乎无法以正确的顺序或语法来获取它们。 There's the question and screenshot below. 下面是问题和屏幕截图。

SQL.zoo Problem#13 SQL.zoo问题#13

You just need to break down your problem. 您只需要分解您的问题。 Remember CASE will check the cases in order... so if the first case evaluates to TRUE then the following tests are never checked for that row. 请记住, CASE将按顺序检查案例...因此,如果第一个案例的评估结果为TRUE则永远不会为该行检查以下测试。

You are getting hung up on a multiple condition case statement. 您正陷入多条件案例陈述中。 Specifically, for the portion you asked about (North America and South America) you need to check two conditions. 具体来说,对于您所询问的部分(北美和南美),您需要检查两个条件。

  1. Is the country in the Caribbean? 该国在加勒比海吗?
  2. Does the name Start with a B or not? 名称是否以B开头?

So, step through it in order of what they asked. 因此,按照他们的要求逐步执行。

  • Oceania becomes Australasia: when continent = 'Oceania' then 'Australasia' 大洋洲成为大洋洲: when continent = 'Oceania' then 'Australasia'
  • Countries in Eurasia and Turkey go to Europe/Asia: when continent = 'Eurasia' or continent = 'Turkey' then 'Europe/Asia' 欧亚大陆和土耳其的国家前往欧洲/亚洲: when continent = 'Eurasia' or continent = 'Turkey' then 'Europe/Asia'
  • Caribbean islands starting with 'B' go to North America, other Caribbean islands go to South America: 以'B'开头的加勒比海岛屿前往北美,其他加勒比海岛屿前往南美:

when continent = 'Caribbean' and name like 'B%' then 'North America'

when continent = 'Caribbean' and name not like 'B%' then 'South America'

Now put it all together... 现在放在一起...

select
  name, 
  continent,
  case 
    when continent = 'Oceania' then 'Australasia' 
    when continent = 'Eurasia' or continent = 'Turkey' then 'Europe/Asia'
    when continent = 'Caribbean' and name like 'B%' then 'North America'
    when continent = 'Caribbean' and name not like 'B%' then 'South America'
    else continent 
  end as NewContinent
from
  world
order by 
  name asc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM