Decode函數說明以及縱橫表的轉化

Decode函數說明

含義解釋: 

  • decode(字段或字段的運算,值1,值2,值3)

         這個函數運行的結果是,當字段或字段的運算的值等於值1時,該函數返回值2,不然返回值3
    固然值1,值2,值3也能夠是表達式,這個函數使得某些sql語句簡單了許多sql

 

  • decode(條件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)

    該函數的含義以下:
  IF 條件=值1 THEN
    RETURN(翻譯值1)
  ELSIF 條件=值2 THEN
    RETURN(翻譯值2)
    ......
  ELSIF 條件=值n THEN
    RETURN(翻譯值n)
  ELSE
    RETURN(缺省值)
  END IF函數

 


 

用法

1.比較大小

select decode( sign(a.salesprice-a.wholesalesprice), --sign 函數大於0返回1,小於0返回-1,0返回0
0,'同樣', '1','價格大', '-1','價格小'), a.salesprice,a.wholesalesprice from hrip.dict_item_charge a

 

2.統計數量

select 
sum(decode(p.sexname,'',1,0)) 男的數量, sum(decode(p.sexname,'',1,0)) 女的數量 from hrip.pati_info_basic p

 

3.子查詢

select decode(b.sexname, '',(select w.patiid from hrip.pati_info_workunit w where w.patiid = b.patiid), '',(select w.patiid from hrip.pati_info_workunit w where w.patiid = b.patiid), '不清楚性別') from hrip.pati_info_basic b

 

其餘

  • 此函數Oracle專用,還能夠用於字符串搜索,主鍵值加一等,靈活運用。

 

ORACLE中縱橫表的轉化

假設有張學生成績表(zb)以下:post

我如今我須要獲得以下的數據spa

用DECODE或者CASE來實現相互轉化:翻譯

select name 姓名, max(case subject when '語文' then result else 0 end) 語文, max(case subject when '數學' then result else 0 end) 數學, max(case subject when '物理' then result else 0 end) 物理 from zb group by name; ---------------------------------------------------------------------- select name 姓名, max(decode(subject, '語文', result, 0)) 語文, max(decode(subject, '數學', result, 0)) 數學, max(decode(subject, '物理', result, 0)) 物理 from zb group by name;

這兩個語句均可以實現咱們的需求。code

反之:blog

select *
  from (select 姓名 as Name, '語文' as Subject, 語文 as Result from hb union all
        select 姓名 as Name, '數學' as Subject, 數學 as Result from hb union all
        select 姓名 as Name, '物理' as Subject, 物理 as Result from hb) t order by name, case Subject when '語文' then
             1
            when '數學' then
             2
            when '物理' then
             3
          end;

 

此時咱們還能夠增長總分,平均分的字段:ip

select *
  from (select 姓名 as Name, '語文' as Subject, 語文 as Result from hb union all
        select 姓名 as Name, '數學' as Subject, 數學 as Result from hb union all
        select 姓名 as Name, '物理' as Subject, 物理 as Result from hb) t order by name, case Subject when '語文' then
             1
            when '數學' then
             2
            when '物理' then
             3
          end;
相關文章
相關標籤/搜索