【问题标题】:Create a column and fill it with a certain value if another condition in a different table is met?如果满足不同表中的另一个条件,则创建一个列并用某个值填充它?
【发布时间】:2020-02-13 16:53:28
【问题描述】:

我要编写一个查询,用于检索公司名称、街道地址的第一行、城市和名为 Address_Type 的列,其值为 SalesLT.CustomerAddress 表中地址类型为“的客户”总公司”。

我有一个名为 Sa.customer 的表,其中包含诸如 First name 、 last name 、 address 等客户信息,还有另一个名为 SalesLT.CustomerAddress 的表,其中包含 Customer ID、Address ID 、 Address_Type 等。在我的查询中,我如果满足 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

【问题讨论】:

  • 向我们展示一些示例表数据和预期结果 - 都是格式化文本,而不是图像。
  • 语法错误。每个 SELECT 只有一个 FROM。
  • 为了使 jarlh 的评论更清楚 - 您的查询应该采用
  • 我想看看你的设计。向表中添加 AddressType 列不仅有助于此查询。像这样一遍又一遍地存储字符串是痛苦的。如果您需要从“主办公室”更改,则必须更新所有地址行。如果这是一个查找表,它会简单得多。但真的你需要看看这里。 minimal reproducible example
  • 您可以只使用'Billing' as address_type,因为where 子句只允许这些地址。

标签: sql sql-server


【解决方案1】:

您可以利用 SQL Server CASE 语句为您的 [Address Type] 列构建一个值,方法是测试该结果元组的 SalesLT.CustomerAddress 字段的值:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多