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

后端 未结 5 1260
孤城傲影
孤城傲影 2020-12-16 10:29

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

This w

相关标签:
5条回答
  • 2020-12-16 10:56

    Another option is to use SUM:

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

    db<>fiddle demo

    0 讨论(0)
  • 2020-12-16 10:57

    Try this way:

    select 
      (
        SELECT 
          "count"(*) as val1 
        from 
          tab1
      ) - (
        SELECT 
          "count"(*) as val2 
        from 
          tab2
      ) as total_count
    
    0 讨论(0)
  • 2020-12-16 11:06

    You can write many query to answer this question like: As I am considering the question as we have table named as STATION and we have to now finding the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table

    Query 1:

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

    Query 2:

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

    Query 3:

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

    All the above mentioned query will work.

    0 讨论(0)
  • 2020-12-16 11:19
    select t1.cnt - t2.cnt
    from (select count(*) as cnt from tab1) as t1
      cross join (select count(*) as cnt from tab2) as t2
    
    0 讨论(0)
  • 2020-12-16 11:20

    for same table you can do this.

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

    0 讨论(0)
提交回复
热议问题