I'm querying the following table:
id | value | applicable |
---|---|---|
id1 | 5 | Unknown |
id1 | 5 | Unknown |
id1 | 6 | Yes |
id 2 | 5 | Unknown |
id 2 | 5 | No |
id 2 | 3 | Unknown |
I would like to replace all "Unknowns" in the applicable column, with the non-unknown values pertaining to each id.
Ideally, I would like to see this:
id | value | applicable |
---|---|---|
id1 | 5 | Yes |
id1 | 5 | yes |
id1 | 6 | Yes |
id 2 | 5 | No |
id 2 | 5 | No |
id 2 | 3 | No |
Sorry if this a very easy question, I'm new to this!
Thank you
Anthony Genovese
2,0673 gold badges22 silver badges34 bronze badges
asked Mar 22, 2021 at 18:10
1 Answer 1
This expects one one value besides of unknown, if this si not the case you must choose another aggregation function
CREATE TABLE table1 ([id] varchar(4), [value] int, [applicable] varchar(7)) ; INSERT INTO table1 ([id], [value], [applicable]) VALUES ('id1', 5, 'Unknown'), ('id1', 5, 'Unknown'), ('id1', 6, 'Yes'), ('id 2', 5, 'Unknown'), ('id 2', 5, 'No'), ('id 2', 3, 'Unknown') ; GO
UPDATE table1 SET table1.[applicable] = t1.[applicable] FROM table1 INNER JOIN (SELECT [id],MIN([applicable]) as [applicable] FROM table1 WHERE [applicable] <> 'Unknown' GROUP BY [id]) t1 ON table1.id = t1.id
GO
SELECT * FROM table1 GO
id | value | applicable :--- | ----: | :--------- id1 | 5 | Yes id1 | 5 | Yes id1 | 6 | Yes id 2 | 5 | No id 2 | 5 | No id 2 | 3 | No
db<>fiddle here
answered Mar 22, 2021 at 18:54
lang-sql
id
three times, once with theunknown
value for theapplicable
column, once withyes
, and once withno
?