If multiple entries have the same ID (tag_num), I would like the columns to be the same. For example, if one row may have a description and another one is null but both have the same ID(tag_num), I’d like the description to be copied to the null row as well.
Before:
--------------------------------------
| tag_num | description | category |
--------------------------------------
| 1 | Description A | A |
| 1 | | |
| 2 | Description B | B |
| 2 | Description B | B |
| 2 | Description B | |
| 3 | Description C | |
| 3 | | |
--------------------------------------
Expected output:
--------------------------------------
| tag_num | description | category |
--------------------------------------
| 1 | Description A | A |
| 1 | Description A | A |
| 2 | Description B | B |
| 2 | Description B | B |
| 2 | Description B | B |
| 3 | Description C | |
| 3 | Description C | |
--------------------------------------
This is the SQL I’ve written so far (for mySQL) but I’m stumped:
SELECT * FROM table
WHERE tag_num IN (
SELECT tag_num
FROM table
GROUP BY tag_num
-- update empty columns here where columns are empty
)
2
Answers
Assuming you’re using Mysql 8+ a windowed aggregate is a possible solution:
If analytic functions are available to you, use them (as Stu said; though, as all values should be just the same, perhaps you don’t have to check whether something is NULL or not):
Alternatively, find target values in a subquery and join it to source data. This option isn’t as good as previous as you have to query the same table twice so performance might suffer if you deal with large tables; you won’t notice any difference on small tables, though.