Question

I have two tables RDC and Cons_Status, rdc has a unique column in it RDC_ConsNO. And against this Consignment Number, there could be multiple records in Cons_Status table as depicted in the image attached. I want to write a query in which I get only one record joined to the status with maximum sts_id. I am using SQL Server 2012.

SELECT STS_ID,RDC_CONSNO,STS_STATUS , RDC_DATE,RDC_CUSTOMER,DEST_NAME FROM RDC LEFT OUTER JOIN CONS_STATUS ON RDC_CONSNO=STS_CONSNO
INNER JOIN DESTINATION ON DEST_ID=RDC_DESTINATION WHERE RDC_CONSNO='HD88300'
ORDER BY STS_ID

Database diagram for the tables

enter image description here

Was it helpful?

Solution

Don't forget to prefix your columns

SELECT ?? FROM RDC
OUTER APPLY
(SELECT TOP 1 * FROM CONS_STATUS
WHERE RDC.RDC_CONSNO = STS_CONSNO
ORDER BY sts_id DESC
) a
INNER JOIN DESTINATION d
ON d.DEST_ID=RDC.RDC_DESTINATION 
WHERE RDC.RDC_CONSNO='HD88300'
ORDER BY a.STS_ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top