通过跳过空值来比较列值?

时间:2019-07-29 13:12:01

标签: sql oracle oracle11g

SQL语句一:

select glaccountid,debit,credit 
from transactionentries 
where glaccountid in (15376);

以上语句返回以下输出:

+------------------------------+
| glaccountid | debit | credit |
+------------------------------+
|  15376      |  1584 |  null  |
+------------------------------+
|  15376      |  null | 1400   |
+------------------------------+

SQL语句二:

select glaccountid,debit,credit 
from transactionentries 
where glaccountid in (15374);

以上语句返回以下结果:

+------------------------------+
| glaccountid | debit | credit |
+------------------------------+
|  15374      |  null | 1584   |
+------------------------------+
|  15374      | 14000 | null   |
+------------------------------+

我正在尝试编写一个查询,该查询返回事务条目,其中15376的借方值不等于15374的贷方值,反之亦然,而忽略了具有NULL值的列。 / p>

我已经尝试过的:

SELECT cpo.glaccountid cpo,cpo.debit,cpo.credit,ba.glaccountid branch, ba.debit,ba.credit 
  FROM transactionentries cpo 
 INNER JOIN transactionentries ba 
    ON cpo.transactionid = ba.transactionid
 WHERE cpo.glaccountid = 15374 
   AND ba.glaccountid = 15376 
   AND (cpo.debit <> ba.credit OR ba.debit <> cpo.credit);

预期输出:

+------------------------------+
| glaccountid | debit | credit |
+------------------------------+
|  15374      |  14000 |  null |
+------------------------------+
|  15376      |  null | 1400   |
+------------------------------+

1 个答案:

答案 0 :(得分:1)

您无法将null当作一个值进行比较,因为Oracle中的null是“没有信息”,而不是一个值。您可能会找到许多很好的答案。

关于查询,如果您只想考虑同时具有两个not null值的记录,这可以是一种不言自明的编辑where情况的方法:

(
  (cpo.debit <> ba.credit and cpo.debit is not null and ba.credit is not null)
or
  (ba.debit <> cpo.credit and ba.debit is not null and cpo.credit is not null)
)

您可以用不同的方式编辑它;这是我能想到的最具可读性的