【问题标题】:Return Multiple Items in the same row (SQL)返回同一行中的多个项目(SQL)
【发布时间】:2015-10-29 08:12:57
【问题描述】:

我正在使用这里的问题练习我的 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

但我不知道如何将送货地址输入第二列。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    需要有某种字段来标识主地址中的哪个地址,哪个是送货地址。假设你有这样一个领域,那么有几种不同的方法可以做到这一点。这是一个条件聚合:

    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 作为送货地址,具体取决于所需的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2018-11-17
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多