SQL Server Replacing values in a table with values in a look up table

6tdlim6h  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(102)

I have data stored in a table that requires specific values to be removed so it can be shared more widely.
The data that needs to be removed will have a key as below:

Data Table
| Statement | Answer |
| ------------ | ------------ |
| First Name | Mike |
| Last Name | Smith |
| Position | Fitter |
| Country | France |
| Years Worked | 25 |

Look up

KeyReturn
First NameRedacted
Last NameRemoved
CountryNot Available

Output:

StatementAnswer
First NameRedacted
Last NameRemoved
PositionFitter
CountryNot Available
Years Worked25

I tried using a join and I tried using SET to match the columns when Statement = Key. Both of these I managed to replace the values in the Answer column with values in Return but it also replaced the values that didn't have a match in the look up column with NULL

Code I have tried:

SELECT *
FROM [Data Table] DATA
LEFT JOIN [Lookup up] DSL
ON DATA.[Statement] = DSL.[Key]

and

UPDATE [Data Table Sanitised]
SET [Answer] = (
SELECT [Return]
FROM [Look up]
WHERE [Key] = [Statement]
)

Both returned:

StatementAnswer
First NameRedacted
Last NameRemoved
PositionNULL
CountryNot Available
Years WorkedNULL
oxf4rvwz

oxf4rvwz1#

Using your example data:

create table #data
(
    [Statement] varchar(20),
    Answer varchar(10)
)

insert into #data values
('First Name','Mike'),
('Last Name','Smith'),
('Position','Fitter'),
('Country','France'),
('Years Worked','25')

create table #lookup
(
    [Key] varchar(20),
    [Return] varchar(20)
)

insert into #lookup values
('First Name','Redacted'),
('Last Name','Removed'),
('Country','Not Available')

This gives the expected output:

select
    d.[Statement],
    coalesce(l.[Return],d.Answer) as Answer
from #data d
left join #lookup l on d.[Statement] = l.[Key]

Result:

StatementAnswer
First NameRedacted
Last NameRemoved
PositionFitter
CountryNot Available
Years Worked25

相关问题