Oracle PL / SQL:两个表之间的count(*)

时间:2018-05-23 15:12:36

标签: sql oracle oracle10g

尝试计算2个表之间的计数差异。

关注this,但获得00923. 00000 - "FROM keyword not found where expected"

SELECT ( SELECT count(*) FROM XE_ERR_OVLP WHERE FLAG = 'E') 
- (SELECT count(*) FROM XE_ERR_RANG WHERE FLAG = 'H' ) as cnt;

如何实现这一目标?

4 个答案:

答案 0 :(得分:5)

那是:

SELECT ( SELECT count(*) FROM XE_ERR_OVLP WHERE FLAG = 'E') 
  - (SELECT count(*) FROM XE_ERR_RANG WHERE FLAG = 'H' ) as cnt 
  from dual;

与其他数据库相比,Oracle需要from子句。您可以使用虚拟表dual

答案 1 :(得分:1)

您需要添加FROM DUAL 您的查询应如下所示

SELECT ( SELECT count(*) FROM XE_ERR_OVLP WHERE FLAG = 'E') 
- (SELECT count(*) FROM XE_ERR_RANG WHERE FLAG = 'H' ) as cnt
FROM DUAL;

答案 2 :(得分:1)

您可以使用UNION ALLSUM

SELECT SUM(c) AS cnt
FROM (SELECT 1 AS c FROM XE_ERR_OVLP WHERE FLAG = 'E'
     UNION ALL
     SELECT -1 FROM XE_ERR_RANG WHERE FLAG = 'H') sub;

答案 3 :(得分:0)

我们还可以仅使用 SUM 来计算计数差异,如下所示。

select ( ( select sum(1) XE_ERR_OVLP WHERE FLAG = 'E' ) 
       - ( select sum(1) XE_ERR_RANG WHERE FLAG = 'H' ) 
    ) cnt from dual;