Mysql行轉列的實現(靜態 動態 統計)

2021-07-15 13:21:38 字數 815 閱讀 5121

應用場景:以學生為單位,查詢出每個學生對應的每個科目的考試成績。

建立示例資料庫表

create table `scores` (

`id` int(11) not null auto_increment,

`user_id` int(11) default null comment '使用者id',

`subject` varchar(100) default null comment '學科',

`score` decimal(5,2) default null comment '分數',

primary key (`id`)

) engine=innodb default charset=utf8;

插入示例資料

insert into `scores` values (1, 1, '哲學', 92);

insert into `scores` values (2, 1, '英語', 71);

insert into `scores` values (3, 1, '體育', 59);

insert into `scores` values (4, 1, '網路技術', 86);

insert into `scores` values (5, 1, '資料結構與演算法', 93);

insert into `scores` values (6, 2, '哲學', 69);

insert into `scores` valu

mysql 動態行轉列 MySQL行轉列

比如乙個單子,多個收據單用逗號隔開,怎麼把這乙個單子所有收據單獨展示出來,行轉成列呢?方法一 這裡需要用到迴圈,首先建立乙個1 10的序列 select rownum rownum 1 as seq from select rownum 0 r,bills limit 0,10 其次依次運用 sub...

MySql動態行轉列

靜態行轉列簡單一點。動態行轉列就需要涉及到儲存過程。需要統計每個班下了多少套秋裝和冬裝,但由於有的學校可能還下了夏裝,每個學校下的款式不一樣,所以這個列是動態的 所以建乙個檢視 如圖 需要把這個行轉為列 如下儲存函式 begin set sql null set ssq null select gr...

Oracle實現動態行轉列

oracle中要實現行轉列的方式有很多種,比如case when else end wm concat 函式,lag over lead over 函式等,以及11g版本後的pivot函式都可實現。可根據具體的需求選取不同的方式。前兩天恰好一朋友問起如何將如下表1動態轉成表2的形式。表1 表2,ch...