i have a table with 2 column : ID and Created Date. For the same ID i have different created dates. i need to update the Created Date based on the oldest date on which that ID was created.
For example, for ID=1 i have at created date null values, 12 april 2016 and 14 oct 2015. In the final tabel i need to update thsi column for ID=1 only with the oldes date: 14 oct 2015.
;WITH cte_min_dates AS (
SELECT ID, MIN(CreatedDate) AS MinCreatedDate
FROM dbo.table_name
GROUP BY ID
HAVING MIN(CreatedDate) IS NOT NULL
)
UPDATE tn
SET CreatedDate = cmd.MinCreatedDate
FROM dbo.table_name tn
INNER JOIN cte_min_dates cmd ON cmd.ID = tn.ID AND (tn.CreatedDate IS NULL OR cmd.MinCreatedDate <> tn.CreatedDate)