繁体   English   中英

如果满足不同表中的另一个条件,则创建一个列并用某个值填充它?

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

我必须编写一个查询来检索公司名称、街道地址的第一行、城市和名为 Address_Type 的列,其中 SalesLT.CustomerAddress 表中的地址类型为“Main Office”的客户的值为“Billing” .

我有一个名为 Sa.customer 的表,其中包含名字、姓氏、地址等客户信息,还有另一个名为 SalesLT.CustomerAddress 的表,其中包含客户 ID、地址 ID、地址类型等。在我的查询中,我要做如果满足 SalesLT.CustomerAddress 表中的条件地址类型 = 'Main Office',则名为“Address Type”的新列的值为“Billing”。

我在需要的地方加入了多个表,并使用 WHERE 命令应用了过滤器。 它必须是一个复合查询,即我必须用命令填充空白,并且我不能在两行之间添加或修改代码。

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

您可以利用 SQL Server CASE语句通过测试该结果元组的 SalesLT.CustomerAddress 字段的值来为[Address Type]列构造一个值:

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

但是,如果您正在处理用户输入的数据,您可能会发现拼写 Main Office 的方法比您想象的要多! 我也会在 CASE 语句中的 CustomerAddress 字段上推荐TRIM()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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