In 1:M relationship get single (record) instead of many records from MANY table

If you have two table caring 1 to many relationship and you want to get records with joins MANY table with only single/top most records then you have to get MANY tables records along with ROW NUMBER. then you can join this with main table with AND condition ROW NUMBER =1

for example:
we have two table Inspection and Inspection_Details. One inspection can have many details but one detail is only of one inspection.
So if we want to get only one inspection with only top/one inspection detail then the query will be,

WITH    INS
          AS ( SELECT   ROW_NUMBER() OVER ( PARTITION BY ID.InspectionId ORDER BY ID.InspectionDetailId DESC ) AS RN ,
                        ID.*
               FROM     dbo.Inspection_Details ID
             )
    SELECT  i.InspectionId ,
            INS.*
    FROM    dbo.Inspection i
            INNER JOIN INS ON i.InspectionId = INS.InspectionId
                              AND INS.RN = 1




******************************************
Another method of doing the same thing is by using  CROSS APPLY

Query is:

SELECT  i.InspectionId ,
        a.*
FROM    dbo.Inspection i
        CROSS APPLY ( SELECT TOP 1
                                *
                      FROM      dbo.Inspection_Details ID
                      WHERE     i.InspectionId = ID.InspectionId
                      ORDER BY  ID.InspectionDetailId ASC
                    ) a

Comments

Popular posts from this blog

TSQL To Get All the Names of tables and Databases whose data have changed in last 24 Hours

To Get All the Names of tables and Databases their data have changed in last 24 Hours And Backup those databases

Apply paging in procedure