WITH tickets AS( SELECT id, addressFk, packages, refFk FROM vn.ticket WHERE refFk = ? ), volume AS( SELECT SUM(volume) volume, MAX(weight)weight FROM tickets t JOIN vn.saleVolume sv ON sv.ticketFk = t.id ), intrastat AS( SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR '. ' ) intrastat FROM tickets t JOIN vn.sale s ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk JOIN vn.intrastat ir ON ir.id = i.intrastatFk ), totalPackages AS( SELECT SUM(packages)packages FROM tickets s ) SELECT tp.packages, io.incotermsFk, ic.name incotermsName, v.weight weight, ca.fiscalName customsAgentName, ca.street customsAgentStreet, ca.nif customsAgentNif, ca.phone customsAgentPhone, ca.email customsAgentEmail, CAST(v.volume AS DECIMAL (10,2)) volume, i.intrastat FROM vn.invoiceOut io JOIN vn.incoterms ic ON ic.code = io.incotermsFk LEFT JOIN vn.customsAgent ca ON ca.id = io.customsAgentFk JOIN volume v JOIN intrastat i JOIN totalPackages tp WHERE `ref` = (SELECT DISTINCT refFk FROM tickets)