Mysql儲存過程 行列轉換

2021-08-30 01:13:05 字數 1862 閱讀 1126

在網上找了些資料,自己動手寫了個行列轉換的儲存過程。

下面片段為表結構:

create table `changeprice` (

`id` bigint(20) not null auto_increment,

`sid` bigint(20) not null,

`datecreated` date not null default current_timestamp,

`price` varchar(50) not null,

primary key (`id`)

) engine=innodb default charset=latin1;

表中插入以下資料:

(1,1,'2009-05-08','30'),

(2,1,'2009-05-10','50'),

(3,1,'2009-05-11','12'),

(4,1,'2009-05-12','20'),

(5,1,'2009-05-14','50'),

(6,1,'2009-05-15','30'),

(7,3,'2009-05-11','12'),

(8,3,'2009-05-12','30'),

(9,3,'2009-05-14','50'),

(10,3,'2009-05-15','30'),

(11,2,'2009-05-08','30'),

(12,2,'2009-05-09','50'),

(13,2,'2009-05-11','12'),

(14,2,'2009-05-13','20'),

(15,2,'2009-05-14','50'),

(16,2,'2009-05-15','30');

現要顯示為:

sid,5-8,5-9,5-10,5-11,5-12...

1, 30, 0, 50,12, 20 ...

2, 30, 50, 0, 12, 0 ...

3, 0, 0, 0, 0, 12 ...

採用mysql儲存過程加上cursor實現。

create procedure test111()

begin

declare done int default 0;

declare strdate date;

declare str char(1000) default '';

declare cur1 cursor for select distinct(date(datecreated)) from changeprice order by datecreated;

declare continue handler for sqlstate '02000' set done=1;

open cur1;

repeat

if not done then

fetch cur1 into strdate;

set str=concat(str, ',', 'sum(if(datecreated=''', strdate, ''', price, 0))', '''', strdate,'''');

end if;

until done end repeat;

set @sqlstring=concat(' select sid ', str, ' from changeprice group by sid ');

prepare sqlstmt from @sqlstring;

execute sqlstmt;

deallocate prepare sqlstmt;

end

mysql行列轉換 mysql行列轉換

1.一維轉二維 上圖為成績表中資料,現希望將資料轉換為下圖。靜態 轉化為二維表後的列名及列數是確定不變的,本例中即course只有數學 語文 英語這三門課。select s name,max if course 數學 score,0 as 數學,max if course 語文 score,0 as...

mysql行列轉換例子 mysql行列轉換示例

現把轉換方法列舉如下 1 縱表轉橫表 縱表結構 tablea name course grade 張三語文 張三數學 張三英語 李四語文 李四數學 橫表結構 tableb name 語文數學 英語張三 李四方法一 select name,sum case course when 語文 then gr...

MySQL 行列轉換

最近在慕課上 看mysql教程 裡面關於行轉列的教程不錯 貼上練習sql 做個記錄 簡單行轉列 select a.user name,sum b.kills from user1 a join user kills b on a.id b.user id group by user name cro...