Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SQL中组合AND和OR_Sql_Database - Fatal编程技术网

在SQL中组合AND和OR

在SQL中组合AND和OR,sql,database,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 | Account

我很难得到这个查询的确切结果

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

如果使用或,请始终使用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)

在中使用
,而不是

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

你似乎对布尔逻辑感到不舒服。我建议在混合

可能的重复项时始终使用括号,以便向OP澄清。。它被解释为:
从tableName中选择isnull(SUM(a.Amount),0)作为WHERE(a.ProgramID=4和a.AccountID=475和a.ActionCode=1)或a.ActionCode=3
,通过添加的副题,您应该能够看到为什么会得到这样的结果;)Ghost和Gordon下面的答案很贴切。我更喜欢你的第二种方式。谢谢你