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

Uce*_*cef 17 sql postgresql

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

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

SELECT "count"(*) AS val1 FROM tab1;
SELECT "count"(*) AS val2 FROM tab2;
SELECT val2-val1;
Run Code Online (Sandbox Code Playgroud)

提前致谢

Rob*_*ert 35

试试这种方式:

select 
  (
    SELECT 
      "count"(*) as val1 
    from 
      tab1
  ) - (
    SELECT 
      "count"(*) as val2 
    from 
      tab2
  ) as total_count
Run Code Online (Sandbox Code Playgroud)


Adi*_*mar 12

对于同一张桌子,你可以这样做。

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


a_h*_*ame 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
Run Code Online (Sandbox Code Playgroud)


小智 6

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

查询1:

select (count(city)-count(distinct city)) from station;
Run Code Online (Sandbox Code Playgroud)

查询2:

select ((select count(city) as ans1 from station)-(select count(distinct city)
       as ans2 from station));
Run Code Online (Sandbox Code Playgroud)

查询3:

select (( select count(city) from station )-( select count(distinct city) from station ))
       as ans;
Run Code Online (Sandbox Code Playgroud)

上述所有查询都将起作用。