2013-01-15 162 views
1

我需要帮助改进对下表查询的WHERE子句:满足WHERE条件 - T-SQL

Key | Name | Role | Location 
111 | Bob | Manager | All Locations 
222 | Jim | Manager | All Locations 
333 | Tim | Sales | Washington 
444 | Roy | Sales | New York 
555 | Lee | Sales | All Locations 
666 | Gus | Sales | All Locations 
777 | Joe | Admin | All Locations 
888 | Jen | Admin | New York 

我需要排除所有的“所有地点”的记录,但保留“所有位置的记录,其中角色是经理。为了得到理想的效果:

Key | Name | Role | Location 
111 | Bob | Manager | All Locations 
222 | Jim | Manager | All Locations 
333 | Tim | Sales | Washington 
444 | Roy | Sales | New York 
888 | Jen | Admin | New York 

我觉得下面的查询会排除所有的位置记录,包括管理者的记录。

SELECT * FROM Table 
WHERE (Location <> 'All Locations' AND Role <> 'Manager') 

回答

0

您应该使用或者替代和

SELECT * FROM Table 
WHERE (Location <> 'All Locations' OR Role = 'Manager') 
1
SELECT * FROM Table 
WHERE (Location != 'All Locations' OR (Location = 'All Locations' AND Role = 'Manager') 
4

你将要展开的WHERE

select * 
from yourtable 
where 
(
    role = 'Manager' 
    and location = 'All Locations' 
) 
or 
(
    location <> 'All Locations' 
) 

SQL Fiddle with Demo

返回结果:

| KEY | NAME | ROLE |  LOCATION | 
---------------------------------------- 
| 111 | Bob | Manager | All Locations | 
| 222 | Jim | Manager | All Locations | 
| 333 | Tim | Sales | Washington | 
| 444 | Roy | Sales |  New York | 
| 888 | Jen | Admin |  New York | 
1

您说“排除所有'所有位置'记录,但保留”所有位置“记录,其中角色是管理器。难道这不是意味着排除的所有位置记录,其中的角色是经理?即,你不想要包含记录111和222?

从德摩根定律,而不是与非B等同于不(A或B)

在你的情况下,一个预测是正的,另一个为负,所以德·摩根将改为:

Not (A And not B) <=> (Not A or B), i.e., 

这意味着包括所有记录不是所有位置或经理。

如果是这样,那么你需要的是:

... Where Location != 'All Locations' Or Role = 'Manager'