salix/db/routines/bs/procedures/comparativeCampaign.sql

40 lines
1.2 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root``localhost` PROCEDURE `bs`.`comparativeCampaign`(vDateFrom DATE, vDateTo DATE)
BEGIN
SELECT deparmentName,
id clientFk,
name clientName,
CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) previousAmmount,
CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) currentAmmount
FROM ((SELECT
d.name deparmentName,
c.id,
c.name,
SUM(s.amount) previousAmmount,
0 currentAmmount
FROM sale s
JOIN vn.`client` c ON s.clientFk = c.id
JOIN vn.department d ON d.id = c.salesDepartmentFk
WHERE s.dated BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR)
AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
GROUP BY d.id, s.clientFk)
UNION ALL
(SELECT
d.name deparmentName,
c.id,
c.name,
0 AS previousAmmount,
SUM(s.quantity * s.price) currentAmmount
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.department d ON d.id = c.salesDepartmentFk
WHERE t.shipped BETWEEN vDateFrom AND vDateTo
GROUP BY d.id, c.id)
) comparative
GROUP BY deparmentName, id
HAVING previousAmmount OR currentAmmount
ORDER BY deparmentName, id;
END$$
DELIMITER ;