1. 程式人生 > >SQL之ROUND、CASE、LIKE語句

SQL之ROUND、CASE、LIKE語句

SQL當中的round函式可以對數值的小數位進行處理,比如保留兩位小數如下所示:

select name,ROUND(population/1000000,2)as population, ROUND(gdp/1000000000,2) as gdp
from world
where continent='South America'

還可以用來除去小數字部分,比如2134變為2000,如下所示:

select name,round(gdp/population,-3)as gdp
from world
where gdp > 1000000000000

Case的使用
如下是將continent是Oceania的替換成Australasia,其他不變:

SELECT name, 
       CASE WHEN continent='Oceania' THEN 'Australasia'
            ELSE continent END
  FROM world
 WHERE name LIKE 'N%'

如下是多個CASE使用的情況

select name,
     CASE WHEN continent='Europe' or continent='Asia' THEN'Eurasia'
          when continent='South America' or continent='North America'
or continent='Caribbean' then 'America' else continent end from world where name like 'A%' or name like 'B%'

使用了CASE同時還有ORDER By 以及like:

select name,continent,
CASE when continent='Oceania' then 'Australasia'
     when continent='Eurasia' or name = '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 from world order by name ASC