縱表和橫表的概念及其相互轉換
橫表就是普通的建表方式,如:主鍵、屬性1、屬性2、屬性3…等很多屬性的鋪陳, 如果變成縱表後,則表結構爲: 主鍵、屬性。例如:
橫表:
縱表:
橫表
優點:一行表示了一個實體記錄,清晰可見,一目瞭然。
缺點:如果現在要給這個表加一個字段,那麼就必須重建表結構。
縱表
優點:如果現在要給這個表加一個字段,只需要添加一些記錄。
缺點:數據描述不是很清晰,而且會造成數據庫數據很多。另如果需要分組統計,要先group by,較繁瑣。
結論
應該把不容易改動表結構的設計成橫表,把容易經常改動不確定的表結構設計成縱表。
縱錶轉橫表
有如下縱表:
將其轉爲橫表:
select
s.student_name,
sum(case s.subject when '語文' then s.score end) as 語文,
sum(case s.subject when '數學' then s.score end) as 數學,
sum(case s.subject when '英語' then s.score end) as 英語
from score_vertical s
group by s.student_name
結果:
橫錶轉縱表
有如下橫表:
將其轉爲縱表:
select s.student_name,
'語文' as 科目,
s.語文 as 成績
from score_horizontal s
union all
select s.student_name,
'數學' as 科目,
s.數學 as 成績
from score_horizontal s
union all
select s.student_name,
'英語' as 科目,
s.英語 as 成績
from score_horizontal s
order by student_name, 科目
結果: