1
I have the following Rigger code, where it makes a select on the main tables (DADF311, DADF313.. ) to insert the result ready in 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 should insert ANOMES with their respective values, my result is repeating as example 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
One detail that may be causing this, would be the DATREG field of the DADF514 table, it is of type INT, and the DATREG field of the DADF311 table is DATETIME