我正在使用此查询:
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日期的记录
答案 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])