Search code examples
sqlinner-joininner-query

How to find Last record in group



Below is my data table:

+----------+--------------+--------+-------+---------------+-------------+--------+
| RegionID | ReceivedDate | FdNo   | FmNo  | FromRegionID  | ToRegionID  | HFlag  |
+----------+--------------+--------+-------+---------------+-------------+--------+
| 26       | 2014-04-10   | 104152 | 1     | 26            | 27          | 1      |
| 26       | 2014-04-10   | 104152 | 1     | 27            | 26          | 0      |
| 26       | 2014-04-10   | 104152 | 2     | 26            | 27          | 1      |
| 26       | 2014-04-10   | 104152 | 2     | 27            | 26          | 0      |
| 26       | 2014-04-10   | 104152 | 3     | 26            | 27          | 1      |
| 26       | 2014-04-10   | 104152 | 3     | 27            | 26          | 0      |
| 26       | 2014-04-10   | 104152 | 4     | 26            | 27          | 1      |
| 26       | 2014-04-10   | 104152 | 4     | 27            | 26          | 0      |
+----------+--------------+--------+-------+---------------+-------------+--------+

I want to select last record from each group of fdNo.In sample table I have given the data with duplicate count of 2 ,in real case it might be 3,4, so on.

expected output :

+----+-------------------------+--------+---+----+----+---+
| 26 | 2014-04-10 15:35:30.000 | 104152 | 1 | 27 | 26 | 0 |
| 26 | 2014-04-10 15:35:30.000 | 104152 | 2 | 27 | 26 | 0 |
| 26 | 2014-04-10 15:35:44.000 | 104152 | 3 | 27 | 26 | 0 |
| 26 | 2014-04-10 15:35:44.000 | 104152 | 4 | 27 | 26 | 0 |
+----+-------------------------+--------+---+----+----+---+


I want to append the Ans Query to my Origininal Query (from which the actual table is brougt)

Raw Query :

SELECT tblreceipt.regionid, 
       tblreceipt.receiveddate, 
       tblreceipt.folderno, 
       tblreceipt.formno, 
       tbltransite.dispatchfromregionid, 
       tbltransite.dispatchtoregionid, 
       tbltransite.horeceivedflag 
FROM   tblreceipt 
       LEFT OUTER JOIN tbltransite 
                    ON tblreceipt.folderno = tbltransite.folderno 
WHERE  tblreceipt.folderno = 104152 

Solution

  • With CTE As (
    select  tblReceipt.RegionID,
            tblReceipt.ReceivedDate, 
            tblReceipt.FolderNo,
            tblReceipt.FormNo,
            tblTransite.DispatchFromRegionID,
            tblTransite.DispatchToRegionID,
            tblTransite.HOReceivedFlag,
            Row_Number() Over(Order By FmNo, HFlag) A Rn
            from     tblReceipt
                          left outer join
                     tblTransite
                          on tblReceipt.FolderNo = tblTransite.FolderNo
            where    tblReceipt.FolderNo = 104152
            )
            Select Top 1 From CTE Order By Rn Desc