各位大蝦,根據欄位1,如果相鄰行相同,則合并為一行,并對欄位2求和。具體如下圖,萬分感謝!

uj5u.com熱心網友回復:
這最好還是拿到代碼里計算。如果必須在資料庫里做,可以寫個存盤程序用游標遍歷uj5u.com熱心網友回復:
謝謝斑竹的回復uj5u.com熱心網友回復:
同意這個問答~
uj5u.com熱心網友回復:
我怎么記得我回答過一次呢。。。--原始資料
create table tests01(name1 varchar(10),score int)
insert into tests01(name1,score)
values("甲",10),("甲",20),("乙",10),("乙",30),("乙",20),("乙",30),("甲",10),("丙",20),("丙",30),("丁",10),("丁",10),("甲",40)
--整合后資料
create table tests01_des(id int primary key auto_increment , name1 varchar(10),score int);
--創建存盤程序
DELIMITER $$
CREATE PROCEDURE `StatisticStore`()
BEGIN
declare done INT DEFAULT 0;
declare name2 varchar(10);
declare score2 int;
DECLARE MAXID INT;
declare cur_test cursor for select name1,score from tests01;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
open cur_test;
repeat
fetch cur_test into name2,score2;
if not done then
begin
if ((select count(1) from tests01_des)=0) then
insert into tests01_des(name1,score) values(name2,score2);
else
begin
if (select name1 from tests01_des order by id desc limit 1)=name2 then
SET MAXID=( select max(id) from tests01_des);
update tests01_des set score = score+score2 where id=MAXID;
else
insert into tests01_des(name1,score) values(name2,score2);
end if;
end;
end if;
end;
end if;
until done end repeat;
close cur_test;
END$$
DELIMITER ;
--呼叫執行程序
call StatisticStore();
--查看資料
select * from tests01;
select* from tests01_des;

uj5u.com熱心網友回復:
這個答案很詳細了
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/13346.html
標籤:MySQL
上一篇:sql統計的sql優化問題
