SELECT J.joborderid,
J.jobtype,
J.jobno,
J.status AS JoborderStatus,
AJ.status AS AirJobStatus,
Isnull(INV.invoiceid, 0) AS INVInvoiceid,
Isnull(INV.invoiceno, 0) AS INVInvoiceNo,
Isnull(INV.statusid, 0) AS INVStatusID,
Isnull(INV.invoicemodeid, 0) AS INVInvoiceModeID
FROM ffs_tbl_joborder J
INNER JOIN ffs_tbl_airjob AJ
ON AJ.airjobid = J.joborderid
AND AJ.jobno = J.jobno
LEFT JOIN (SELECT joborderid,
jobno,
jobtype,
invoiceid,
Isnull(invoiceno, 0) AS InvoiceNo,
statusid,
invoicemodeid,
createddate,
minchk
FROM (SELECT INV.joborderid,
INV.jobno,
INV.jobtype,
INV.invoiceid,
INV.invoiceno,
INV.statusid,
INV.invoicemodeid,
INV.createddate,
Row_number()
OVER(
partition BY joborderid, jobtype
ORDER BY createddate DESC) AS Minchk
FROM ffs_tbl_invoice INV
WHERE jobtype IN ( 'AirJob', 'AirHouseJob' )) AS t1
WHERE minchk = 1) INV
ON INV.joborderid = J.joborderid
AND INV.jobno = J.jobno
AND INV.jobtype = J.jobtype
WHERE INV.jobtype IN ( 'AirJob', 'AirHouseJob' )
AND J.joborderid = 2802
GROUP BY J.joborderid,
J.jobtype,
J.jobno,
J.status,
AJ.status,
INV.invoiceid,
INV.invoiceno,
INV.statusid,
INV.invoicemodeid