參考自:http://www.blogjava.net/willpower88/archive/2008/10/28/237186.html
decode(條件,值1,返回值1,返回值2) 對應的轉換是:case when 條件 = '值1' then '返回值1' else '返回值2' end
舉例:
oracle:
select decode(sex,NULL,'男','女') as sex,name,age,score From student_score_table
mysql實現(轉換后):
select case when sex=null then '男' else '女' end as sex,name,age,score From student_score_table
在mysql中有decode()是這樣解釋的:一種是加密,另外一種是比較。
在Oracle中:
語法:DECODE(control_value,value1,result1[,value2,result2…] ,[default_result]);control _value試圖處理的數值。DECODE函數將該數值與后面的一系列的偶序相比較,以決定返回值。
value1是一組成序偶的數值。如果輸入數值與之匹配成功,則相應的結果將被返回。對應一個空的返回值,可以使用關鍵字NULL於之對應
result1 是一組成序偶的結果值。
default_result 未能與任何一個值匹配時,函數返回的默認值。
例如:
selectdecode( x , 1 , ‘x is 1 ’, 2 , ‘x is 2 ’, ‘others’) from dual
當x等於1時,則返回‘x is 1’。
當x等於2時,則返回‘x is 2’。
否則,返回others’。
需要,比較2個值的時候,可以配合SIGN()函數一起使用。
SELECT DECODE( SIGN(5 -6), 1 'Is Positive', -1, 'Is Nagative', 'Is Zero')
同樣,也可以用CASE實現:
1 SELECT CASE SIGN(5 - 6) 2 3 WHEN 1 THEN 'Is Positive' 4 5 WHEN -1 THEN 'Is Nagative' 6 7 ELSE 'Is Zero' END 8 9 FROM DUAL
此外,還可以在Order by中使用Decode。
例如:表table_subject,有subject_name列。要求按照:語、數、外的順序進行排序。這時,就可以非常輕松的使用Decode完成要求了。
select * from table_subject order by decode(subject_name, '語文', 1, '數學', 2, , '外語',3)