The Problem
I have this table. (You can also view it in DBFiddle.)
| Id | Version | Item No. | Notes |
|---|---|---|---|
| 1 | NULL | 31 | |
| 2 | 1 | 31 | tasty |
| 3 | 2 | 31 | kinda tasty |
| 4 | NULL | 32 | |
| 5 | 1 | 32 | meh |
| 6 | 2 | 32 | alright |
| 7 | 3 | 32 | fabulous |
| 8 | NULL | 33 | ambivalent |
| 9 | 1 | 33 | gross |
| 10 | 2 | 33 | puke |
The 1st column is the primary key. The 2nd and 3rd column are integers. The 4th column is a VARCHAR.
For every unique Item No. where its Version is NULL, I want to look at the record with the highest Version value, take the content of its Notes field, and copy it over.
This is much easier to understand visually; after the command is run, the table should look like this:
| Id | Version | Item No. | Notes |
|---|---|---|---|
| 1 | NULL | 31 | kinda tasty |
| 2 | 1 | 31 | tasty |
| 3 | 2 | 31 | kinda tasty |
| 4 | NULL | 32 | fabulous |
| 5 | 1 | 32 | meh |
| 6 | 2 | 32 | alright |
| 7 | 3 | 32 | fabulous |
| 8 | NULL | 33 | ambivalent |
| 9 | 1 | 33 | gross |
| 10 | 2 | 33 | puke |
Explanation of the Changes
- for Item No. 31, "kinda tasty" was copied over because it's in the record with the highest Version number, and the target cell is not occupied.
- for Item No. 32, "fabulous" was copied over for the same reason.
- "puke" was NOT copied over to replace "ambivalent", because the target cell is occupied.
The Question
What is the query to achieve this in SQL Server?
I know that I need a way of grouping records together by Item No., find the one with the highest Version value, take its Notes value, and copy it to the record where the Version is NULL, but I am having trouble translating this to SQL.