[英]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'.我必须编写一个查询来检索公司名称、街道地址的第一行、城市和名为 Address_Type 的列,其中 SalesLT.CustomerAddress 表中的地址类型为“Main Office”的客户的值为“Billing” .
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.我有一个名为 Sa.customer 的表,其中包含名字、姓氏、地址等客户信息,还有另一个名为 SalesLT.CustomerAddress 的表,其中包含客户 ID、地址 ID、地址类型等。在我的查询中,我要做如果满足 SalesLT.CustomerAddress 表中的条件地址类型 = 'Main Office',则名为“Address Type”的新列的值为“Billing”。
I've joined multiple tables wherever required and have applied the filter using WHERE command.我在需要的地方加入了多个表,并使用 WHERE 命令应用了过滤器。 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:您可以利用 SQL Server
CASE
语句通过测试该结果元组的 SalesLT.CustomerAddress 字段的值来为[Address Type]
列构造一个值:
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!但是,如果您正在处理用户输入的数据,您可能会发现拼写 Main Office 的方法比您想象的要多! I would recommend
TRIM()
on the CustomerAddress field in the CASE statement as well.我也会在 CASE 语句中的 CustomerAddress 字段上推荐
TRIM()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.