SQL:如何根据条件从同一数据源创建两列?

时间:2016-11-09 19:16:29

标签: mysql

我刚刚开始学习SQL,并且正在网上做一些练习题。 我在这里遇到了这个问题(页面上的#11):http://sqlzoo.net/wiki/AdventureWorks_hard_questions

以下是我们将针对此问题使用的3个表的架构:

CustomerAW (CustomerID,FirstName,MiddleName,LastName,CompanyName,EmailAddress)

CustomerAddress (CustomerID,AddressID,AddressType)

地址(AddressID,AddressLine1,AddressLine2,City,StateProvince,CountyRegion,PostalCode)

问题是:

对于在达拉斯拥有“主办公室”的每位客户,请显示“主办公室”的AddressLine1和“送货”地址的地址1 - 如果没有送货地址,请将其留空。每个客户使用一行。

以下是我的代码:

SELECT CustomerID, AddressType,  AddressLine1
FROM CustomerAW
JOIN CustomerAddress
USING (CustomerID)
JOIN Address
USING (AddressID)
WHERE AddressType IN 'Main Office'
AND  City = 'Dallas'
;

以下是我得到的输出:

Result:
CustomerID  AddressType AddressLine1
112         Main Office P.O. Box 6256916
130         Main Office Po Box 8259024
165         Main Office 2500 North Stemmons Freeway
201         Main Office Po Box 8035996
256         Main Office 99828 Routh Street, Suite 825.

但我不知道如何在单独的栏目中显示送货地址。 以便标题成为 “CustomerID,AddressType,MainOfficeAddress,ShippingAddress”。如问题中所述,如果没有送货地址,请将其留空。

更新

如何在不使用“视图”的情况下执行此操作?我正在测试的网站不允许我创建视图......

我尝试了什么

好吧,我尝试过不同的方法来实现这一点,其中一种方法是在SELECT语句中编写子查询:

SELECT c.CustomerID,  
(
SELECT a.AddressLine1 FROM Address a
JOIN CustomerAddress ca
USING (AddressID)
WHERE ca.AddressType = 'Main Office'
) AS MainOfficeAddress
FROM CustomerAW c
;

但是我会得到错误,说“子查询返回的行数超过1行”。

我也尝试了类似下面的内容(实际上没有一个工作):

SELECT c.CustomerID,  b.AddressLine1, e.AddressLine1
FROM CustomerAW c
JOIN
(
SELECT * FROM CustomerAddress ca
JOIN Address a
USING (AddressID)
WHERE ca.AddressType IN 'Main Office'
) AS b
USING (CustomerID)
JOIN
(
SELECT * FROM CustomerAddress ca
JOIN Address a
USING (AddressID)
WHERE ca.AddressType IN 'Shipping'
) AS e
USING (CustomerID)
;

SELECT c.CustomerID, AddressType,  AddressLine1 AS MainOfficeAddress, 
(
    SELECT a.AddressLine1 FROM Address a
    JOIN CustomerAddress ca USING (AddressID)
    WHERE ca.CustomerID IN c.CustomerID
    AND ca.AddressType = 'Shipping'
) AS ShippingAddress
FROM CustomerAW c
JOIN CustomerAddress ca
USING (CustomerID)
JOIN Address
USING (AddressID)
WHERE ca.AddressType IN ('Main Office')
AND City = 'Dallas'
;

非常感谢任何帮助!希望我不是在问一个愚蠢的问题。

1 个答案:

答案 0 :(得分:1)

您应该使用'内部联接'。 写上面相同的代码,创建一个简单的视图,我的意思是

create view ee as
(
    SELECT CustomerID, AddressType,  AddressLine1
    FROM CustomerAW
    JOIN CustomerAddress
    USING (CustomerID)
    JOIN Address
    USING (AddressID)
    WHERE AddressType IN 'Main Office'
    AND  City = 'Dallas'
 )   ;

然后写..

    create view rr as
    (
    SELECT CustomerID, AddressType,  AddressLine1
    FROM CustomerAW
    JOIN CustomerAddress
    USING (CustomerID)
    JOIN Address
    USING (AddressID)
    WHERE AddressType IN 'Shipping Address'
    );

然后进行视图ee和rr

的内连接
select CustomerID, AddressType, MainOfficeAddress, ShippingAddress
from ee
inner join
rr
on ee.customerID=rr.CustomerID

希望这有助于......;)