Forum Discussion
saikumar86k
Dec 23, 2024Copper Contributor
Need Help To Get Last Record Based On Column Value
Hi , Below is the sample data, and I need to get the latest record based on last_modified_date, and [active/inactive] columns. ID, Name are the key columns and based on last modified date i need ...
IrfanDBA
Feb 20, 2025Copper Contributor
This query should return the Active row if we have one otherwise returns the latest row based on Last_Modified_Date.
;WITH StatusRanking AS (
SELECT
c_ID,
[C_Name],
[Active/InActive] ,
Last_Modified_Date,
ROW_NUMBER() OVER (
PARTITION BY C_ID
ORDER BY
CASE
WHEN [Active/InActive] = 'Active' THEN 1
ELSE 2
END,
Last_Modified_Date DESC
) AS RowNum
FROM #T
)
SELECT
C_ID,
[C_Name],
[Active/InActive],
Last_Modified_Date, RowNum
FROM StatusRanking
WHERE RowNum = 1;