簡體   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