Share via

SQL Server: creating a column in query that combines two columns

Sullivan, Matthew 21 Reputation points
2020-10-09T17:51:04.51+00:00

I'm pulling a query of demographic data for a list of current clients, specifically state of residence. I have our base customer data table that has some of the information then an additional view that is made up of appended data. I'm trying to create the column "state_residence" by merging the two data sets via left join but want the query to execute a if base_customer state is null then appended_data else base_customer.

In the past I used SAS and was able to do this but am unsure how to execute that query using MS SQL Server. Can anyone assist?

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


Answer accepted by question author

Guoxiong 8,221 Reputation points
2020-10-09T18:20:36.563+00:00
DECLARE @Customer TABLE (
    Customer varchar(100),
    Base_State varchar(2),
    Append_State varchar(2)
);
INSERT INTO @Customer VALUES
('Joe Smith', 'CO', NULL),
('Mike Johnson', 'CO', 'CO'),
('Stacy Blue', NULL, 'CO'),
('Penny G', NULL, 'FL'),
('Jimmy Dean', 'MT', NULL),
('Money Mike', NULL, NULL);

SELECT *, ISNULL(Base_State, Append_State) AS State_Residence
FROM @Customer;

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.