根據您輸入:
- 首先報告的部分只有一個記錄,所以我已經使用以下結構
CREATE TABLE `ResultPart1` (
`ReportDate` date NOT NULL,
`Amount` float DEFAULT NULL,
`total_orders` int(11) DEFAULT NULL
)
insert into ResultPart1 select '2017-01-01', 500.00 , 50;
2.本報告的第二部分將有不同的地方,這裏使用的地方是一個字也沒有使用關鍵字。
CREATE TABLE `ResultPart2` (
`Place` varchar(50) NOT NULL,
`Total` int(11) DEFAULT NULL
)
insert into ResultPart2()
Select 'Hyderabad', 100 union
Select 'Bangalore' , 100 union
Select 'Chennai' , 200 union
Select 'Mumbai' , 100;
3.創建存儲過程
CREATE PROCEDURE `new_procedureDashboard`()
BEGIN
Declare vPlaceCount int;
Declare vquery varchar(1000);
declare vPlace varchar(1000);
declare vPlaceTotal int;
-- select * from ResultPart1;
-- Select * from ResultPart2;
CREATE TEMPORARY TABLE IF NOT EXISTS Table_ResultPart2
(
Id int NOT NULL AUTO_INCREMENT,
Place varchar(100),
PlaceTotal int ,
PRIMARY KEY (id)
);
insert into Table_ResultPart2(Place,PlaceTotal)
Select distinct Place,Total from ResultPart2;
SET vPlaceCount=(Select count(*)from Table_ResultPart2);
WHILE vPlaceCount>0 DO
SET vPlace=(Select Place from Table_ResultPart2 where Id=vPlaceCount);
SET vPlaceTotal=(Select PlaceTotal from Table_ResultPart2 where Id=vPlaceCount);
SET vquery=concat("", "alter table ResultPart1 add " ,vPlace ," int ;");
Select vquery into @AddColumn;
PREPARE stmt FROM @AddColumn;
-- Select @AddColumn;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET vquery="";
-- Select vPlace,vPlaceTotal;
-- Update
SET SQL_SAFE_UPDATES = 0;
SET vquery=concat("", "update ResultPart1 SET " ,vPlace ," = " ,vPlaceTotal ," where 1=1 ;");
Select vquery into @UpdateColumn;
-- select @UpdateColumn;
PREPARE stmt1 FROM @UpdateColumn;
-- Select @AddColumn;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET SQL_SAFE_UPDATES = 1;
SET vPlaceCount=vPlaceCount-1;
SET vPlace="" ;
END WHILE;
Select * from ResultPart1;
drop TEMPORARY TABLE IF EXISTS Table_ResultPart2;
END
說明: 新增使用循環在主所得表所需的柱,和更新的值使用循環新放置(添加)列的位置。您將需要在存儲過程中進行更改,因爲我使用了永久表(ResultPart1和ResultPart2)。
4.結果
ALTER語句以防萬一砸列要重新運行存儲過程。
alter table ResultPart1 drop column Hyderabad;
alter table ResultPart1 drop column Bangalore;
alter table ResultPart1 drop column Chennai;
alter table ResultPart1 drop column Mumbai;
請檢查下面的答案。 –