我正在使用以下问题练习SQL:http://sqlzoo.net/wiki/AdventureWorks_hard_questions
我的第一个遇到了问题。我将在此处重新发布,因此您不必单击链接。
对于在达拉斯拥有“总公司”的每个客户,请显示“总公司”的AddressLine1和“发运”地址的AddressLine1-如果没有送货地址,请将其留空。每个客户使用一行。
涉及的表是CustomerAW(CustomerID为PKey,我认为是唯一相关字段),CustomerAddress(具有CustomerID,AddressID和AddressType项目)和Address(具有AddressID,AddressLine1和City是相关字段)。
我现在所拥有的是:
SELECT A.AddressLine1,
FROM Address A, CustomerAddress CA, CustomerAW C
WHERE C.CustomerID = CA.CustomerID AND A.City = 'Dallas' AND A.AddressID = CA.AddressID
GROUP BY C.CustomerID
但我不知道如何将送货地址输入第二栏。
最佳答案
需要某种字段来标识主要地址中的哪个地址,以及哪个是运送地址。假设您有这样一个领域,那么有两种不同的方法可以做到这一点。这是带有条件聚合的一个:
select c.customerid,
max(case when ca.addresstype = 'Main' then a.addressline1 end) as main,
max(case when ca.addresstype = 'Ship' then a.addressline1 end) as ship
from customeraw c
join customeraddress ca on c.customerid = ca.customerid
join address a on ca.addressid = a.addressid
group by c.customerid
having max(case when ca.addresstype = 'Main' then a.city end) = 'Dallas'
另一种选择是多次连接到
address
表-一种用于总部,另一种用于运输:select c.customerid,
a.addressline1 as main,
a2.addressline1 as ship
from customeraw c
join customeraddress ca on c.customerid = ca.customerid
join address a on ca.addressid = a.addressid and ca.addresstype = 'Main'
join address a2 on ca.addressid = a2.addressid and ca.addresstype = 'Ship'
where a.City = 'Dallas'
使用此选项时,根据所需结果,您可能需要使用
outer join
作为送货地址。