Replacing existing column with values based on condition from other values SQL Server

cwtwac6a  于 2023-05-05  发布在  SQL Server
关注(0)|答案(2)|浏览(167)

I want to replace values from my table with values from query result. The query looks like this:

select *,
    case
        when car_model = 'Altima' THEN 'Nissan'
        when car_model = 'F-150' THEN 'Ford'
        when car_model = 'Civic' THEN 'Honda'
        when car_model = 'Silverado' THEN 'Chevrolet'
    END
FROM car_sales_data
WHERE car_model IN ('Altima','F-150','Civic','Silverado')

Basically, this is data cleaning task to do. I am working on it for few hours now and I can't come to any working solution...

**Important thing is that I want these new values to be saved in a table so I can do some analysis afterwards. **

I've tried different things like INSERT INTO, creating table, none of it worked for me. I am a beginner :)

tgabmvqs

tgabmvqs1#

update car_sales_data
set car_model=
case
        when car_model = 'Altima' THEN 'Nissan'
        when car_model = 'F-150' THEN 'Ford'
        when car_model = 'Civic' THEN 'Honda'
        when car_model = 'Silverado' THEN 'Chevrolet'
        else car_model
    END

WHERE car_model IN ('Altima','F-150','Civic','Silverado')

Base Data

create table car_sales_data(car_model varchar(100))
insert into car_sales_data values('Altima')
insert into car_sales_data values('F-150')
insert into car_sales_data values('Civic')
insert into car_sales_data values('Civic')
xriantvc

xriantvc2#

The script below will check if your results table exists, and drop it if so (to allow multiple runs). It then selects the required data into dbo.test from your current table, and select the results. I've set it to put the results into a table called dbo.test ; make sure this name isn't in use already for something else.

/* DELETE OUTPUT TABLE IF IT EXISTS */

if exists
(
    select name from sys.tables 
    where 
        name = 'test' 
        and OBJECT_SCHEMA_NAME(object_ID) = 'dbo'
)
begin 
    drop table dbo.test 
end

select *,
    case
        when car_model = 'Altima' THEN 'Nissan'
        when car_model = 'F-150' THEN 'Ford'
        when car_model = 'Civic' THEN 'Honda'
        when car_model = 'Silverado' THEN 'Chevrolet'
    END

/*  NEW table NAME HERE */

into dbo.test

FROM car_sales_data
WHERE car_model IN ('Altima','F-150','Civic','Silverado')

select * from dbo.test

相关问题