SELECT * FROM invoiceOut io JOIN invoiceOutSerial ios ON io.serial = ios.code JOIN (SELECT t.refFk, ir.id code, ir.description description, CAST(SUM(IFNULL(i.stems, 1) * s.quantity) AS DECIMAL(10,2)) stems, CAST(SUM(CAST(IFNULL(i.stems, 1) * s.quantity * IF(ic.grams, ic.grams, i.density * ic.cm3delivery / 1000) / 1000 AS DECIMAL(10,2)) * IF(sub.weight, sub.weight / vn.invoiceOut_getWeight(?), 1)) AS DECIMAL(10,2)) netKg, CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100 )) AS DECIMAL(10,2)) subtotal FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk JOIN vn.intrastat ir ON ir.id = i.intrastatFk LEFT JOIN ( SELECT t2.weight FROM vn.ticket t2 WHERE refFk = ? AND weight LIMIT 1 ) sub ON TRUE WHERE t.refFk = ? AND i.intrastatFk GROUP BY i.intrastatFk UNION ALL SELECT NULL AS refFk, NULL AS code, NULL AS description, 0 AS stems, 0 AS netKg, IF(CAST(SUM((ts.quantity * ts.price)) AS DECIMAL(10,2)), CAST(SUM((ts.quantity * ts.price)) AS DECIMAL(10,2)), 0) AS subtotal FROM vn.ticketService ts JOIN vn.ticket t ON ts.ticketFk = t.id WHERE t.refFk = ?) sub WHERE io.`ref` = ? AND ios.isCEE ORDER BY sub.code;