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

64 lines
1.9 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`vivosMuertos`()
BEGIN
/**
* Devuelve el número de clientes nuevos y muertos,
* dependiendo de la fecha actual.
*
* @param @datSTART Fecha de inicio a buscar
* @param @datEND Fecha de finalización a buscar
*/
SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE());
DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos;
CREATE TEMPORARY TABLE tmp.VivosMuertos
SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto
FROM vn2008.Clientes c
JOIN
(SELECT DISTINCT yearMonth
FROM vn2008.time
WHERE date BETWEEN @datSTART
AND @datEND ) tm
LEFT JOIN
(SELECT DISTINCT tm.yearMonth, io.clientFk Id_Cliente , 1 as Compra
FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = io.issued
WHERE io.issued BETWEEN @datSTART
AND @datEND) f ON f.yearMonth = tm.yearMonth
AND f.Id_Cliente = c.Id_Cliente;
UPDATE tmp.VivosMuertos vm
JOIN
(SELECT MIN(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = io.issued
WHERE io.issued BETWEEN @datSTART AND @datEND
GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente
SET Nuevo = 1;
SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos;
UPDATE tmp.VivosMuertos vm
JOIN (
SELECT MAX(tm.yearMonth) firstMonth, io.clientFk Id_Cliente
FROM vn.invoiceOut io
JOIN vn2008.time tm ON tm.date = io.issued
WHERE io.issued BETWEEN @datSTART AND @datEND
GROUP BY io.clientFk) fm ON fm.firstMonth = vm.yearMonth
AND fm.Id_Cliente = vm.Id_Cliente
SET Muerto = 1
WHERE yearMonth < @lastYearMonth;
SELECT * FROM tmp.VivosMuertos;
END$$
DELIMITER ;