Oracle中縱橫表的轉化


橫表就是普通的建表方式,如一個表結構為:主鍵、字段1、字段2、字段3......如果變成縱表后,

則表結構為:主鍵、字段代碼、字段值。而字段代碼則為字段1、字段2、字段3。

縱表對從數據庫到內存的映射效率是有影響的,但細一點說也要一分為二:縱表的初始映射要慢一些;

縱表的變更的映射可能要快一些,如果只是改變了單個字段時,畢竟橫表字段比縱表要多很多。

橫表的好處是清晰可見,一目了然,但是有一個弊端,如果現在要把這個表加一個字段,那么就必須重建表結構。

對於這種情況,在縱表中只需要添加一條記錄,就可以添加一個字段,所消耗的代價遠比橫表小,

但是縱表的對於數據描述不是很清晰,而且會造成數據庫數量很多,兩者各有利弊。

實際工作中,我們經常會遇到縱橫表的轉化,很簡單的例子,假設有張學生成績表(zb)如下:

我現在我需要得到如下的數據

如何才能實現呢,這就需要用到我們上次說的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;

這兩個語句都可以實現我們的需求。

同樣的,如果我們的成績表(hb)是:


而要求得到的是


的話,

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;

此時我們還可以增加總分,平均分的字段:

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
        union all
        select 姓名 as Name,
               '平均分' as Subject,
               cast((語文 + 數學 + 物理) * 1.0 / 3 as decimal(18, 2)) 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
            when '平均分' then
             4
            when '總分' then
             5
          end;

以上就是所謂的縱橫表的轉化。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM