我很难在此查询中获得准确的结果
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
答案 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)
你似乎对布尔逻辑感到不舒服。我建议您在混合AND
和OR
时始终使用括号。