sqlconcatenationdistinctdense-rankpartition-by

How to get the last record from the duplicate records in SQL?


I want to get the last record from the duplicate records and want the non-duplicate records also.

As depicted in the below image I want to get row number 4, 5, 7 and 9 in my output.

[[Sql data table Output](https://i.sstatic.net/EZ2fF.png)](https://i.sstatic.net/EZ2fF.png)

Here, In the below image the ** Main table** was shown. From which I have to concat first two columns and then from that new column I need the last row of duplicate records and the non-duplicate rows also.

enter image description here

I have tried with the given below SQL code.

DECLARE @dense_rank_demo AS TABLE (
    Bid INT,
    cid INT,
    BCode NVARCHAR(10)
);
    
INSERT INTO @dense_rank_demo(Bid,cid,BCode)
VALUES(2393,1,'LAX'),(2394,54,'BRK'),(2395,57,'ONT'),(2393,1,'SAN'),(2393,1,'LAX'),(2393,1,'BRK'),(2394,54,'ONT'),(2395,57,'SAN'),(2394,1,'ONT');

    
SELECT * FROM @dense_rank_demo;

SELECT 
  CONCAT([Bid],'_',[cid]) as [Key],BCode,DENSE_RANK() over( order by CONCAT([Bid],'_',[cid])) 
     
        
    from @dense_rank_demo

Solution

  • From the SQL code I found that there is no column on which we can apply order by for getting the expected Result.

    So that, I have add one column name Id and done some other changes for getting expected output.

    Here I am Sharing the code in which I have done some changes.

    DECLARE @dense_rank_demo AS TABLE (
    ID INT IDENTITY(1,1),
    Bid INT,
    cid INT,
    BCode NVARCHAR(10));
    DECLARE @tableGroupKey TABLE
    (
        dr bigint,
        [Key] VARCHAR(50)
    )   
    INSERT INTO @dense_rank_demo(Bid,cid,BCode)
    VALUES(2393,1,'LAX'),
    (2394,54,'BRK'),
    (2395,57,'ONT'),
    (2393,1,'SAN'),
    (2393,1,'LAX'),
    (2393,1,'BRK'),
    (2394,54,'ONT'),
    (2395,57,'SAN'),
    (2394,1,'ONT');
    with [drd] as
    (
       select
        concat([Bid],'_',[cid]) as [Key],
        BCode,
        dense_rank() over(partition by concat([Bid],'_',[cid]) order by ID) as 
    [dr]   
      from @dense_rank_demo
    )
    INSERT INTO @tableGroupKey(dr,[Key])
    select MAX(dr) dr,[Key]
    from [drd]
    GROUP BY [Key]
    SELECT *,CONCAT(Bid,'_',cid) AS [Key] FROM  @dense_rank_demo [drd]
    select Result.* FROM
    (
      SELECT *,CONCAT(Bid,'_',cid) AS [Key] ,
      dense_rank() over(partition by concat([Bid],'_',[cid]) order by ID) as 
    [dr]  
    FROM @dense_rank_demo [drd]
    ) as [Result]
    INNER JOIN @tableGroupKey [gk] ON
    [Result].[Key] = [gk].[Key] AND [gk].dr = [Result].dr
    ORDER BY [Result].ID
    

    The Expected output is as below:

    [Output] enter image description here