mysql5中使用過程實現行轉列

realji發表於2008-05-27

簡單到網上搜了一下,沒有發現mysql有類似oracle 的decode函式實現行轉列,有不少用過程實現動態行轉列,試了一下,不適合我用,參考mysql5的幫助,寫個個過程,記錄備忘。其中用到了遊標,關於遊標的使用文件裡給的例子也不錯,反正我就只會那麼用。。。

DELIMITER $$

DROP PROCEDURE IF EXISTS `hrb_yd`.`proc_hrb_yd_stat`$$

CREATE DEFINER=`root`@`192.168.96.1` PROCEDURE `proc_hrb_yd_stat`(IN $G_id INTEGER(10))
BEGIN
declare v_name VARCHAR(255);
declare v INT DEFAULT 0;
declare v1 INT DEFAULT 0;
declare v2 INT DEFAULT 0;
declare v3 INT DEFAULT 0;
declare v4 INT DEFAULT 0;
declare v5 INT DEFAULT 0;
declare v6 INT DEFAULT 0;
declare a int ;
declare b varchar(255);
DECLARE done INT DEFAULT 0;
declare cur1 cursor for select id,name from hrb_yd_admin where g_id=$G_id ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

select count(id) into v from hrb_yd_admin where g_id=$G_id;
open cur1;
repeat
fetch cur1 into a,b;
if not done then
select count(id) into v1 from hrb_yd_visit_table where user_id=a and visit_way='實地走訪' ; /*實地走訪次數*/
select count(id) into v2 from hrb_yd_visit_table where user_id=a and visit_way='電話' ; /*--電話拜訪方式次數*/
select count(id) into v3 from hrb_yd_visit_table where user_id=a and visit_way='E—mail' ; /*--emianl拜訪方式次數*/
select count(id) into v4 from hrb_yd_visit_table where user_id=a and visit_way ='' ; /*--其他拜訪方式次數*/
select count(id) into v5 from hrb_yd_visit_table where user_id=a and visit_un_purpose='是'; /*--推薦成功數*/
select count(id) into v6 from hrb_yd_visit_table where user_id=a and visit_un_purpose='否'; /*--未推薦成功數*/
select b,v1,v2,v3,v4,v5,v6;
end if;
until done end repeat;
close cur1;

END$$

DELIMITER ;

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7425608/viewspace-1004695/,如需轉載,請註明出處,否則將追究法律責任。

相關文章