salix/db/routines/vn2008/procedures/percentil.sql

31 lines
750 B
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`percentil`()
BEGIN
DECLARE max_range INT;
DROP TEMPORARY TABLE IF EXISTS previa;
CREATE TEMPORARY TABLE previa
SELECT @posicion:= @posicion +1 as Posicion, Id_Cliente, Total FROM (
SELECT Id_Cliente, Total FROM (
SELECT Id_Cliente, SUM(Importe) as Total
FROM Facturas
INNER JOIN Clientes USING(Id_Cliente)
INNER JOIN (SELECT @posicion := 0) sub_pos
WHERE invoice
AND YEAR(Fecha) = YEAR(util.VN_CURDATE())
GROUP BY Id_Cliente) sub
ORDER BY Total
) sub2;
SELECT COUNT(*) INTO max_range FROM previa;
UPDATE Clientes SET percentil = 0;
UPDATE Clientes INNER JOIN previa USING(Id_Cliente)
SET Clientes.percentil = ROUND(Posicion *100 / max_range,0);
END$$
DELIMITER ;