I have the following trigger code, where it makes a select in the main tables (DADF311, DADF313 ..) to insert the ready result into the secondary table (DADF514):
DELIMITER $$
CREATE TRIGGER ta_dadf311 AFTER INSERT ON dadf311 FOR EACH ROW
BEGIN
DELETE FROM dadf514 WHERE datreg = NEW.datreg;
INSERT INTO dadf514(datreg, codreg, nomreg, totnot, quanti)
SELECT DATE_FORMAT(dadf311.datreg, '%Y%m') AS datreg, dadf311.codreg AS codreg,
(CASE WHEN dadf311.nomreg IS NULL THEN 'SEM REGIÃO' ELSE dadf311.nomreg END) AS nomreg,
SUM(dadf313.valtot + dadf313.valfre) AS totnot,
SUM(dadf313.quanti) AS quanti
FROM dadf311
LEFT JOIN dadf313 ON (dadf311.tipnot = dadf313.tipnot) AND (dadf311.numnot = dadf313.numnot)
LEFT JOIN dadf016 ON (dadf311.natope = dadf016.codigo)
WHERE
dadf311.tipnot = 'NS' AND
dadf311.para01 = '00' AND
DATE_FORMAT(dadf311.datreg, '%Y%m') = DATE_FORMAT(NEW.datreg, '%Y%m') AND
dadf016.para10 = '01'
GROUP BY DATE_FORMAT(dadf311.datreg, '%Y%m'), dadf311.codreg;
END;$$
DELIMITER ;
The problem is in the grouping, where I should insert ANOMES with their respective values, my result is repeating as shown below:
datreg codreg nomreg totnot quanti
------ ------ ----------- ----------- -----------
201712 0 SEM REGIÃO 3670.0000 2.0000
201712 0 SEM REGIÃO 4979.2300 53.0000
201712 0 SEM REGIÃO 7239.1300 59.0000
201712 0 SEM REGIÃO 7239.1300 59.0000
201712 0 SEM REGIÃO 10909.1300 61.0000
201712 0 SEM REGIÃO 14579.1300 63.0000
201712 0 SEM REGIÃO 15751.8700 78.0000
A detail that may be causing this would be the DATF field of table DADF514, it is of type INT, and the DATF field of table DADF311 is DATETIME