SQL Server查询使用多个where子句

时间:2016-09-21 01:16:51

标签: sql-server

enter image description here大家好我在这里有一个示例表

我正在使用此查询:

SELECT 
    PART_NUMBER, DATE, [WH-IN], [WH-OUT], [END-BAL] 
FROM 
    TABLE1 
WHERE 
    PART_NUMBER = 'TR131305R'  
    AND DATE <= '2016-05-30' 
    AND [WH-IN] = 'W1' 
    OR [WH-OUT] = 'W1' 

问题是它还获取了大于2016-05-30日期的记录

2 个答案:

答案 0 :(得分:2)

问题在于您的OR声明,它会抓取任何符合此条款的记录:

PART_NUMBER = 'TR131305R'  
and DATE <= '2016-05-30' 
and [WH-IN] = 'W1' 

或任何匹配的记录:

OR [WH-OUT] = 'W1'

用括号修正:

SELECT PART_NUMBER, DATE, [WH-IN], [WH-OUT], [END-BAL] 
FROM TABLE1 
WHERE PART_NUMBER = 'TR131305R'  
and DATE <= '2016-05-30' 
and ([WH-IN] = 'W1' --wrap this clause in ()
or [WH-OUT] = 'W1')

答案 1 :(得分:1)

您需要parenthesis

目前,您的查询Where子句将按此处理

WHERE (PART_NUMBER = 'TR131305R' and DATE <= '2016-05-30' and [WH-IN] = 'W1')
or [WH-OUT] = 'W1' 

因为AND的优先级高于OR。因此,请使用括号以适当的顺序应用过滤器。

SELECT PART_NUMBER, DATE, [WH-IN], [WH-OUT], [END-BAL] 
FROM TABLE1 
WHERE PART_NUMBER = 'TR131305R'  
and DATE <= '2016-05-30' 
and ([WH-IN] = 'W1' or [WH-OUT] = 'W1')

或者您可以撤消IN运营商

SELECT PART_NUMBER, DATE, [WH-IN], [WH-OUT], [END-BAL] 
FROM TABLE1 
WHERE PART_NUMBER = 'TR131305R'  
and DATE <= '2016-05-30' 
and 'W1' in ([WH-IN] , [WH-OUT])