1 mysql縱橫表轉換

2021-09-25 11:47:01 字數 1717 閱讀 7189

使用縱表的優勢在於增加某種型別資料時不需要改變表結構。如課程中增加了化學。

使用橫表的優勢在於欄位多,表述能力強,從而資料條目少。

case when的使用

sum函式和group by的使用

create table table_a

( `姓名` varchar(20),

`課程` varchar(20),

`成績` int

);insert into table_a(`姓名`,`課程`,`成績`) values("張三","語文",60);

insert into table_a(`姓名`,`課程`,`成績`) values("張三","數學",70);

insert into table_a(`姓名`,`課程`,`成績`) values("張三","英語",80);

insert into table_a(`姓名`,`課程`,`成績`) values("李四","語文",90);

insert into table_a(`姓名`,`課程`,`成績`) values("李四","數學",100);

select 姓名, 

sum(case `課程` when '語文' then `成績` else 0 end) as '語文',

sum(case `課程` when '數學' then `成績` else 0 end) as '數學',

sum(case `課程` when '英語' then `成績` else 0 end) as '英語'

from table_a

group by 姓名;

可以看出,課程分類轉化成為了結果表的字段,多個記錄合成一條記錄,橫表減少了資料量

union的使用

create table table_b

( `姓名` varchar(20),

`語文` int,

`數學` int,

`英語` int

);insert into table_b(`姓名`,`語文`,`數學`,`英語`) values("張三",60,70,80);

insert into table_b(`姓名`,`語文`,`數學`,`英語`) values("李四",90,100,0);

select 姓名, '語文' as 課程,語文 as '成績' from table_b

union

select 姓名, '數學' as 課程,語文 as '數學' from table_b

union

select 姓名, '英語' as 課程,英語 as '成績' from table_b

order by 姓名,課程

可以看出,每條記錄以課程的種類劃分一分為三了

MySQL資料庫縱橫表轉換

1.縱表 score 目標 切換為橫表 sql語句為 select name as 姓名 max case subject when 語文 then value else 0 end as 語文 max case subject when 數學 then value else 0 end as 數學...

縱橫表轉換學習

動態橫表轉縱表 建表語句 if not object id class1 is null drop table class1 gocreate table class1 student nvarchar 2 數學 int,物理 int,英語 int,語文 int insert class1 sele...

mysql優化(1) mysql事務

事務是mysql等關係型資料庫區別於nosql的重要方面 隨著發展nosql資料庫也開始有了事物的概念 是保證資料一致性的重要手段。本文將首先介紹mysql事務相關的基礎概念,然後介紹事務的acid特性,並分析其實現原理。事務由乙個或多個sql語句組成乙個整體,如果所有的語句執行成功那麼修改將會全部...