使用不同的邮政编码从同一销售区域获取销售人员

时间:2012-11-25 04:34:58

标签: sql sql-server-2008

我正在尝试展示与William居住在同一城市的客户。在我的customer表中,我的邮政编码为zipCode列。在我的city表格中,我将城市名称设为cityName

表格城市

zipCode (PK) cityName, stateCode   

表客户

customerId (PK) customerName, customerAddress, zipCode (FK)

我的查询到目前为止......

SELECT 
    cu2.customerName AS 'Customer Name', 
    ci2.cityName AS 'City Name'
FROM 
    customer as cu
INNER JOIN 
    city as ci ON cu.zipCode = ci.zipCode
INNER JOIN 
    city as ci2 ON ci.cityName = ci2.cityName
INNER JOIN 
    customer as cu2 ON ci2.zipCode = cu2.zipCode
                    AND cu2.customerName <> cu.customerName
WHERE 
    cu2.customerName = 'William'

它没有显示任何结果,因为我认为只有当他所在的城市有两个其他邮政编码时才检查威廉的邮政编码。他是91709,cityNAME还有91708和91710.我需要让那个cityNAME中的其他客户。

2 个答案:

答案 0 :(得分:0)

我会将您的架构视为:

  

客户(customerid,customerName,cityid,...)

     

city(cityid,cityName,zip,...)

要检索与'William'居住在同一城市的客户,您需要

SELECT cust.customerName, cit.city_name
FROM customer cust
JOIN city cit ON cust.cityid = cit.cityid
WHERE cit.cityid IN (
     SELECT cit2.cityid
     FROM city cit2
     JOIN customer cust2 ON cit2.cityid = cust2.cityid
     WHERE cust2.customerName = 'William'
)

答案 1 :(得分:0)

SELECT ct.customerName
FROM city c JOIN customer ct ON c.ZipCode = ct.ZipCode
WHERE c.CityName IN (
                     SELECT c.CityName
                     FROM customer ct JOIN city c ON ct.ZipCode = c.ZipCode 
                     WHERE ct.CustomerName = 'William'
                     )