选择具有一个相同和一个不同列的行

时间:2013-03-03 21:39:43

标签: sql northwind

我正在尝试列出所有美国客户的公司名称与任何员工不在同一个州(或地区)。 它应返回10行。我已经使用了以下查询

SELECT Customers.CompanyName
FROM Customers
WHERE Customers.Country='USA'
  AND Customers.Region IN
    (SELECT Customers.Region
     FROM Customers
     GROUP BY Customers.Region HAVING COUNT(Customers.Region)=1);

但它只返回6.

数据库是 northwind 。 **公司名称


here is the output
Old World Delicatessen
Let's Stop N Shop
Save-a-lot Markets
The Cracker Box
Rattlesnake Canyon Grocery
Split Rail Beer & Ale**

2 个答案:

答案 0 :(得分:4)

试试这个

SELECT CompanyName
  FROM Customers
 WHERE Country='USA' AND 
       Region NOT IN
           (SELECT DISTINCT Region
              FROM Employees 
             WHERE Region IS NOT NULL);

输出

CompanyName
----------------------------------------
Great Lakes Food Market
Hungry Coyote Import Store
Let's Stop N Shop
Lonesome Pine Restaurant
Old World Delicatessen
Rattlesnake Canyon Grocery
Save-a-lot Markets
Split Rail Beer & Ale
The Big Cheese
The Cracker Box

(10 row(s) affected)

在您的问题中,您说您需要所有美国客户的公司名称,这些客户与任何员工不在同一州(或地区)。但是在您的查询中,您试图从客户表中获取区域。

更新:我相信你知道但是以防万一:

子查询(NULL)中WHERE Region IS NOT NULL值的显式检查至关重要。没有它,查询将成功运行但不会返回任何行。

SELECT CompanyName
  FROM Customers
 WHERE Country='USA' AND 
       Region NOT IN
           (SELECT DISTINCT Region
              FROM Employees);

输出:

CompanyName
----------------------------------------

(0 row(s) affected)

我想你想要完成的练习是为了确保你知道子查询中的NULL。

答案 1 :(得分:1)

您的查询根本不会检查Employees表格!看看:

SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND NOT EXISTS(SELECT 1 FROM Employees WHERE Employees.Region = Customers.Region)

SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND  Customers.Region NOT IN (SELECT DISTINCT Employees.Region FROM Employees WHERE Employees.Region IS NOT NULL)

两个查询都返回:

Great Lakes Food Market         OR
Hungry Coyote Import Store      OR
Let's Stop N Shop               CA
Lonesome Pine Restaurant        OR
Old World Delicatessen          AK
Rattlesnake Canyon Grocery      NM
Save-a-lot Markets              ID
Split Rail Beer & Ale           WY
The Big Cheese                  OR
The Cracker Box                 MT