salix/db/routines/vn/procedures/ticket_WeightDeclaration.sql

51 lines
1.9 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_WeightDeclaration`(vClientFk INT, vDated DATE)
BEGIN
DECLARE vTheorycalWeight DECIMAL(10,2);
DECLARE vRealWeight DECIMAL(10,2);
DECLARE vRatio DOUBLE;
SELECT IFNULL(sum(tob.description),0) INTO vRealWeight
FROM vn.ticketObservation tob
JOIN vn.observationType ot ON ot.id = tob.observationTypeFk
JOIN vn.ticket t ON t.id = tob.ticketFk
WHERE ot.description = 'Peso Aduana'
AND t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleVolume sv ON sv.saleFk = s.id
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk
WHERE t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated);
SET vRatio = vRealWeight / vTheorycalWeight;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight;
CREATE TEMPORARY TABLE tmp.ticketWeight
ENGINE = MEMORY
SELECT i.intrastatFk,
ib.ediBotanic,
FLOOR(sum(s.quantity)) as quantity,
CAST(vRatio * SUM(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight) ) AS DECIMAL(10,2)) physicalWeight,
o.code as countryCode,
vDated as Dated
FROM vn.ticket t
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.saleVolume sv ON sv.saleFk = s.id
JOIN vn.item i ON i.id = s.itemFk
LEFT JOIN vn.itemBotanicalWithGenus ib ON ib.itemFk = i.id
LEFT JOIN vn.origin o ON o.id = i.originFk
WHERE t.clientFk = vClientFk
AND t.shipped BETWEEN vDated AND util.dayend(vDated)
GROUP BY ib.ediBotanic, o.code;
END$$
DELIMITER ;