sqlsql-server-2019

Get latest row based by date grouped by concat


I have an issue where I'm trying to retrieve the latest Date created row out of a ConCat column. But getting an error that it's an invalid name. So I'm guessing you can't do it this way?

Unworking Code:

     SELECT
 [USER ID],
 [GROUP ID],
 [DATE CREATED],
concat([USER ID], '_', [GROUP ID]) as CONCAT
         
  FROM [TABLE1]
     
  where
  [DATE CREATED] in ( SELECT MAX([DATE CREATED]) from [TABLE1] group by CONCAT)`

TABLE enter image description here

RESULT NEEDED enter image description here


Solution

  • The logic for the original query is likely wrong, anyway, becuase it might allow showing rows from one User ID/Group ID pair that happen to match the max Created Date from a different User ID/Group ID pair.

    Instead, this may be a job for a windowing function

    WITH Numbered As
    (
        SELECT
            [USER ID],
            [GROUP ID],
            [DATE CREATED],
            row_number() over (Partition By [User ID], [Group ID] Order By [Date Created] DESC) rn         
        FROM [TABLE1]
    )
    SELECT
        [User ID],
        [Group ID],
        [Date Created],
        [USER ID] + '_' + [GROUP ID] as [Concat]
    FROM Numbered
    WHERE rn = 1
    

    Or, you might be able to do this completely within a GROUP BY

    SELECT
        [USER ID],
        [GROUP ID],
        MAX([DATE CREATED]) AS [Date Created],
        [USER ID] + '_' + [GROUP ID] as CONCAT        
    FROM [TABLE1]
    GROUP BY [User ID], [Group ID]     
    

    But I suspect this is contrived for the question, and the actual query has more columns in play.