CREATE DEFINER=`mysql`@`%` PROCEDURE `test`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
-- удалим клон если он есть
DROP TABLE IF EXISTS `clone_data`;
-- склонируем таблицу что бы оставить в целостности основную таблицу
SHOW CREATE TABLE `data`;
CREATE TABLE `clone_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`card_number` varchar(20) DEFAULT NULL,
`date` datetime NOT NULL,
`volume` float NOT NULL,
`service` varchar(100) NOT NULL,
`address_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `clone_data` (`id`, `card_number`, `date`, `volume`, `service`, `address_id`)
SELECT `id`, `card_number`, `date`, `volume`, `service`, `address_id` FROM `data`; -- заполняем данные из основной таблице
SELECT COUNT(*) INTO @nrow FROM `clone_data` WHERE SIGN(volume)=1;
WHILE @nrow > 0 DO
SELECT volume, id, address_id INTO @x_volume, @x_id, @x_address_id FROM clone_data WHERE SIGN(volume)=1 LIMIT 1;
SELECT volume, id INTO @y_volume, @y_id FROM clone_data WHERE id = @x_id+1 AND address_id = @x_address_id LIMIT 1;
UPDATE clone_data SET volume = @xvolume + @yvolume WHERE id = @yid;
DELETE FROM clone_data WHERE id = @xid;
SET @nrow := @nrow -1;
END WHILE;
END