SELECT * FROM invoiceOut io JOIN invoiceOutSerial ios ON io.serial = ios.code JOIN( SELECT ir.id code, ir.description, iii.stems, iii.net netKg, iii.amount subtotal FROM vn.invoiceInIntrastat iii LEFT JOIN vn.invoiceIn ii ON ii.id = iii.invoiceInFk LEFT JOIN vn.invoiceOut io ON io.ref = ii.supplierRef LEFT JOIN vn.intrastat ir ON ir.id = iii.intrastatFk WHERE io.`ref` = ? UNION ALL SELECT NULL code, 'Servicios' description, 0 stems, 0 netKg, IF(CAST(SUM((ts.quantity * ts.price)) AS DECIMAL(10,2)), CAST(SUM((ts.quantity * ts.price)) AS DECIMAL(10,2)), 0) 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;