sql應用行轉列與列轉行

2021-08-01 08:00:32 字數 1675 閱讀 6629

一、行轉列例項:

場景:今天運營人員讓我提取每個使用者在某種交易型別下每年的交易總金額。

表結構:

create table `orders` (

`id` int(11) not null auto_increment,

`user_id` varchar(10) collate utf8_bin default null comment '使用者號',

`trade_type` varchar(10) collate utf8_bin default null comment '交易型別(pay.bank付款到銀行、pay.quick快捷支付、pay.gate閘道器支付)',

`trans_amount` int(11) default null comment '交易金額',

`trans_time` datetime default null comment '交易時間',

primary key (`id`)

);測試資料如下

實現sql如下:

select

user_id,

date_format(trans_time,'%y'),

sum(case trade_type when 'pay.bank' then trans_amount else 0 end) as '付款到銀行',

sum(case trade_type when 'pay.gate' then trans_amount else 0 end) as '閘道器支付',

sum(case trade_type when 'pay.quick' then trans_amount else 0 end) as '快捷支付'

from

orders

group by

user_id,date_format(trans_time,'%y');

執行結果:

分析:通過case when then else end 實現了行專列的功能,從而實現了需求。

二、列轉行例項

場景:目前資料庫中存在一張表記錄了學生在某次考試中語文、數學、英語的分數。想要通過列轉行功能實現一行中只包含一科成績

表結構:

create table score(

id int not null primary key,

student_id int,

cn_score int, 

math_score int,

en_score int

);測試資料:

列轉行sql實現:

select student_id, '語文'  as course, cn_score as score from score

union

select student_id, '數學'  as course, math_score as score from score

union

select student_id, '英語'  as course, en_score as score from score

執行結果:

總結:通過union或者union all 可以實現。但是要搞清楚union和union all的區別

2、對排序的處理: union將會按照欄位的順序進行排序;union all 只是簡單的將兩個結果合併後返回。

3、效率上:很明顯union all 效率更高

SQL 行轉列,列轉行

行列轉換在做報表分析是還是經常會遇到的 行列轉換就是如下圖所示兩種展示形式互相轉換 只是做測試,建表比較隨意 create table student name varchar 20 subject int 10 score int 10 insert into student name,subje...

python 列轉行 SQL 行轉列,列轉行

sql 行轉列,列轉行 行列轉換在做報表分析時還是經常會遇到的,今天就說一下如何實現行列轉換吧。行列轉換就是如下圖所示兩種展示形式的互相轉換 行轉列假如我們有下表 select from student pivot sum score for subject in 語文,數學,英語 通過上面 sql...

sql 行轉列,列轉行整合

原始資料及結構如下 when 語文 then t.score else 0 end 語文,sum case t.subject when 數學 then t.score else 0 end 數學 sum case t.subject when 英語 then t.score else 0 end ...