nutopython07119014
nutopython07119014

Reputation: 76

Create a column and fill it with a certain value if another condition in a different table is met?

I've to write a query that retrieves the company name, first line of the street address, city, and a column named Address_Type with the value 'Billing' for customers where the address type in the SalesLT.CustomerAddress table is 'Main Office'.

I've a table called Sa.customer which has the Customer Info like First name , last name , address etc. and another table called SalesLT.CustomerAddress which has Customer ID, Address ID , Address_Type etc. In my query I've to make a new column named "Address Type" with value "Billing" if the condition address type in SalesLT.CustomerAddress table = 'Main Office' is met.

I've joined multiple tables wherever required and have applied the filter using WHERE command. It has to be a compounded query i.e I have to fill the blank with a command and I cannot add or modify the code between the two lines.

SELECT CompanyName, AddressLine1, City, ___ AS Address_Type
FROM SalesLT.Customer AS c
JOIN SalesLT.CustomerAddress AS ca  
  ON c.Customer_ID = ca.Customer_ID  ###-- join based on Customer_ID   
FROM SalesLT.Address AS a       ### -- join another table  
  ON a.Address_ID = ca.Address_ID   ###-- join based on AddressID
WHERE AddressType = 'Main Office'; ###-- filter for where the correct AddressType

Upvotes: 0

Views: 1307

Answers (1)

mgrollins
mgrollins

Reputation: 651

You can utilize the SQL Server CASE statement to construct a value for your [Address Type] column by testing the value of the SalesLT.CustomerAddress field for that result tuple:

SELECT ...,
  CASE 
    WHEN SalesLT.CustomerAddress LIKE 'Main Office' THEN 'BILLING'
    ELSE ''
  END AS [Address Type],
  ...
FROM ...
WHERE ...

However, you will probably find that there are more ways to spell Main Office than you would think if you are dealing with user entered data! I would recommend TRIM() on the CustomerAddress field in the CASE statement as well.

Upvotes: 1

Related Questions