简体   繁体   中英

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 ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM