SQL PostgreSQL中基于2张表计算两次count(*)查询结果的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21701094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:01:13  来源:igfitidea点击:

Calculate the difference between results of two count(*) queries based on 2 tables in PostgreSQL

sqlpostgresql

提问by Ucef

I want to calculate the difference between the results of 2 count(*)-type SELECT queries executed on 2 separate tables of my PostgreSQL database.

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

This what I'm currently using (however I should be able to wrap it all up into a single SELECT statement):

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

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

Thanks in advance

提前致谢

回答by Robert

Try this way:

试试这个方法:

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

回答by a_horse_with_no_name

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

回答by Aditya Tomar

for same table you can do this.

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

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

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

回答by Lukasz Szozda

Another option is to use SUM:

另一种选择是使用SUM

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

db<>fiddle demo

db<>小提琴演示