I have a table of items that can be arranged into groups. The table contains an attribute column with string values, as an example I chose color. For some items, the color column is empty.
| ItemID | Group | Color |
|---|---|---|
| 001 | A | 'blue' |
| 002 | A | 'blue' |
| 003 | A | 'blue' |
| 004 | A | 'blue' |
| 005 | A | |
| 101 | B | 'red' |
| 102 | B | 'red' |
| 103 | B | |
| 104 | B | |
| 105 | B | 'green' |
From this table I want to select only the items that do not have a color assigned yet and display a proposed color in a new column. The proposed color should be taken from the item with the highest ID value within each group.
The desired output should look like this:
| ItemID | Group | Proposed Color |
|---|---|---|
| 005 | A | 'blue' |
| 103 | B | 'green' |
| 104 | B | 'green' |
I have no idea how to select specific values from the color column based on values from another column (in this case ItemID) and assign them to a different row within my table. Any help (also keywords describing the concept associated with my problem...) would be greatly appreciated!
(edit) This is what I've tried so far:
WITH temp_id AS (
SELECT max(ItemID), GroupName
FROM myTable
WHERE Color IS NOT NULL
GROUP BY GroupName
)
SELECT myTable.*, temp_id.*
FROM myTable
JOIN temp_id
ON temp_id.groupName = myTable.groupName;
But the output is missing the color column and I wasn't able to add a condition WHERE Color IS NOT NULL to my outer selection.