2013-01-15 199 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'