根据PostgreSQL中的2个表计算两个count(*)查询结果之间的差异

时间:2014-02-11 11:53:14

标签: sql postgresql

我想计算2 count(*) - 在我的PostgreSQL数据库的2个独立表上执行的SELECT查询的结果之间的差异。

这就是我目前正在使用的(但是我应该可以将它全部包装到单个SELECT语句中):

SELECT "count"(*) AS val1 FROM tab1;
SELECT "count"(*) AS val2 FROM tab2;
SELECT val2-val1;

提前致谢

5 个答案:

答案 0 :(得分:31)

尝试这种方式:

select 
  (
    SELECT 
      "count"(*) as val1 
    from 
      tab1
  ) - (
    SELECT 
      "count"(*) as val2 
    from 
      tab2
  ) as total_count

答案 1 :(得分:6)

select t1.cnt - t2.cnt
from (select count(*) as cnt from tab1) as t1
  cross join (select count(*) as cnt from tab2) as t2

答案 2 :(得分:1)

您可以编写许多查询来回答此问题,例如: 我正在考虑这个问题,因为我们有一个名为STATION的表,我们现在必须查找表中CITY条目的总数与表中不同CITY条目的数量之间的差异

查询1:

select (count(city)-count(distinct city)) from station;

查询2:

select ((select count(city) as ans1 from station)-(select count(distinct city)
       as ans2 from station));

查询3:

select (( select count(city) from station )-( select count(distinct city) from station ))
       as ans;

上述所有查询都可以使用。

答案 3 :(得分:0)

另一种选择是使用SUM

SELECT SUM(val) AS result
FROM (SELECT count(*) AS val FROM tab2
      UNION ALL
      SELECT -count(*) FROM tab1) sub;

db<>fiddle demo

答案 4 :(得分:0)

对于同一张表,您可以执行此操作。

select (count(abc)-count(DISTINCT xyz)) from tab;