在SQL中组合AND和OR

时间:2016-07-12 16:13:40

标签: sql database

我很难在此查询中获得准确的结果

SELECT isnull(SUM(a.Amount), 0) FROM tableName as a 
WHERE a.ProgramID = 4 and a.AccountID = 475 and a.ActionCode = 1 OR a.ActionCode = 3

我的表

 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
|  AMOUNT  |  ProgramID  |  AccountID  |  ActionCode  |
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
|  500     |  4          |  475        |  1           |
|  1000    |  4          |  475        |  1           |
|  1500    |  4          |  370        |  3           |
- - - - - - - - - - - - - - - - - - - - - - - - - - - -

我得到1500

的结果,而不是获得总金额3000

2 个答案:

答案 0 :(得分:4)

如果使用OR,请始终使用parens。

SELECT isnull(SUM(a.Amount), 0)
FROM tableName as a 
WHERE a.ProgramID = 4
and a.AccountID = 475
and (
       a.ActionCode = 1
    OR a.ActionCode = 3
)

或者我将如何写它:

SELECT isnull(SUM(a.Amount), 0)
FROM tableName as a 
WHERE a.ProgramID = 4
and a.AccountID = 475
and a.ActionCode IN (1,3)

答案 1 :(得分:3)

使用IN代替OR

SELECT COALESCE(SUM(a.Amount), 0)
FROM tableName a 
WHERE a.ProgramID = 4 and a.AccountID = 475 and
      a.ActionCode IN (1, 3)

你似乎对布尔逻辑感到不舒服。我建议您在混合ANDOR时始终使用括号。