How can I T-SQL update records with same PlayerName and PlayerCode but different season value with BornDateKey field corresponding to 2021-2022 season. The input and output I want to do is as follows.
Input:
PlayerName | PlayerCode | Season | BornDateKey |
---|---|---|---|
Lionel Messi | d70ce98e | 2020-2021 | |
Lionel Messi | d70ce98e | 2021-2022 | 19870624 |
Robert Lewandowski | 8d78e732 | 2020-2021 | |
Robert Lewandowski | 8d78e732 | 2021-2022 | 19880821 |
Output (expected):
PlayerName | PlayerCode | Season | BornDateKey |
---|---|---|---|
Lionel Messi | d70ce98e | 2020-2021 | 19870624 |
Lionel Messi | d70ce98e | 2021-2022 | 19870624 |
Robert Lewandowski | 8d78e732 | 2020-2021 | 19880821 |
Robert Lewandowski | 8d78e732 | 2021-2022 | 19880821 |
CodePudding user response:
Using an updatable CTE:
WITH cte AS (
SELECT *, MAX(BornDateKey) OVER (PARTITION BY PlayerCode) AS MaxBornDateKey
FROM yourTable
)
UPDATE cte
SET BornDateKey = MaxBornDateKey
WHERE BornDateKey IS NULL;
If you instead want to view your data this way, then just select from the above CTE and use MaxBornDateKey
as the BornDateKey
value.