2016-08-22 56 views
0

我需要從「世界」表中拉出並添加CASE WHEN語句以使其非洲大陸名稱'Caribbean'在國家'名稱'爲'B'時變爲'北美' ',但是當名稱不是'B%'時,那麼大陸將會='南美洲'。還需要按ASC順序進行命名。具有多種條件和排序的案例陳述

我知道所有的命令來做到這一點,但似乎無法讓他們在正確的順序或語法。下面是問題和屏幕截圖。

SQL.zoo Problem#13

+5

告訴我們一些你已經嘗試使我們能更好地瞭解您所需要的解釋。也不要讓社區爲此工作,將示例數據放在您的問題中,並且使您的條件更易於理解,而不僅僅是簡單地放在段落列表中? – Matt

+0

使用案件陳述的早期逃避方法(一旦條件滿足,它會退出案例)......'當大陸='加勒比'並且名稱像'B%'那麼'北美'當continent ='加勒比'然後'南美'' – xQbert

回答

0

你只需要打破你的問題。請記住CASE將按順序檢查個案...因此,如果第一個個案的評估結果爲TRUE,則不會爲該行檢查以下測試。

你越來越掛在多個條件的case語句。具體而言,對於您詢問的部分(北美和南美),您需要檢查兩個條件。

  1. 是加勒比海國家嗎?
  2. 名稱以B開頭還是不開頭?

因此,按照他們要求的順序進行。

  • 大洋洲變成大洋洲:在歐亞大陸和土耳其進入歐洲/亞洲when continent = 'Oceania' then 'Australasia'
  • 國家:when continent = 'Eurasia' or continent = 'Turkey' then 'Europe/Asia'
  • 加勒比島嶼以「B」去北美,其他加勒比島嶼去南美:

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

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

現在把它放在一起......

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 
+0

感謝一堆!對不起,沒有更好地格式化問題,我將在未來。但非常感謝您的幫助! –

+0

不用擔心@MitchCorreia我知道這是你第一次。不要忘記接受正確的答案,並提供有用的答案。 – scsimon