SQL Server 2008通过知道邮政编码显示城市名称

时间:2012-11-25 21:52:35

标签: sql sql-server-2008

我正在尝试展示与William居住在同一城市的客户。此查询获取其邮政编码并查找具有其邮政编码的任何客户。我需要根据邮政编码找到城市NAME的客户。每个城市名称都有几个邮政编码。

表格城市

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中的其他客户。

3 个答案:

答案 0 :(得分:1)

我认为这样做。

SELECT
  allCustomer.customerName,
  allCity.cityName
FROM Customer finder
  JOIN City finderCity
   ON finder.zipCode = finderCity.ZipCode
  JOIN City allCity
    ON finderCity.CityName = allCity.CityName
    AND finderCity.StateCode = allCity.StateCode
  JOIN Customer allCustomer
    ON allCity.ZipCode = allCustomer.ZipCode
WHERE finder.customerName = 'William'
  and allCustomer.customerName != 'William'

一些注意事项:

  • 如果customerName不是唯一的,那么我们需要更好地识别威廉。
  • 仅在ON子句中指定连接条件...不要在此处设置过滤条件。
  • City(作为一个概念)由City表中的多行表示,这会引起混淆。

答案 1 :(得分:1)

这个SQL会在模拟表上执行它(我自己尝试过):

SELECT customer.customerName, city.cityName FROM customer INNER JOIN city on city.zipCode = customer.zipCode WHERE city.cityName = (

SELECT city.cityName FROM city WHERE zipCode = (
SELECT city.zipCode FROM customer
INNER JOIN city ON customer.zipCode = city.zipCode
WHERE customer.customerName = 'William'
)

)

答案 2 :(得分:0)

Select cityName,customerName from customer
Join City on Customer.zipCode = City.ZipCode
Where 
And customer.customerName = 'William'
Group by cityName, customerName