PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Bagaimana cara menghitung jumlah INNER bergabung dan menghitung jumlah semua item?

Jika Anda membuat dua kueri Anda Kompatibel dengan Serikat, Anda dapat menggabungkan hasil dan menggabungkannya dengan kueri tambahan:

    SELECT payer, 
           sum(churned_accounts) AS "churned_count",
           sum(total_accounts) AS "total_count" 
    FROM (
      SELECT CAST(payor_id AS CHAR(50)) AS "payer", 
             count(*) as "churned accounts", 
             0 AS "total accounts" 
      FROM paid_users_no_more 
      INNER JOIN paid_users 
        ON paid_users_no_more.user_id=paid_users.user_id 
      WHERE paid_users.payment_start_date NOT BETWEEN '2015-08-01 00:00:00'::timestamp AND '2015-08-30 23:59:59'::timestamp 
      AND paid_users_no_more.payment_stop_date BETWEEN '2015-08-01 00:00:00'::timestamp AND '2015-08-30 23:59:59'::timestamp 
      GROUP BY paid_users.payor_id

      UNION

      SELECT CAST(paid_users.payor_email AS CHAR(50)) AS "payer", 
             0 AS "churned accounts", 
             count(*) AS "total accounts" 
      FROM paid_users 
      WHERE paid_users.payment_start_date NOT BETWEEN '2015-08-01 00:00:00'::timestamp AND '2015-08-30 23:59:59'::timestamp 
      GROUP BY paid_users.payor_email
    ) as All_Accounts

Memiliki 0 AS "total_accounts" dan 0 AS "churned_accounts" berarti kedua kueri memiliki bidang yang sama, yang membuat UNION mungkin.




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Array string Ruby / Rails ke sisipan PostgreSQL

  2. Docker - Bagaimana menjalankan perintah psql di wadah postgres?

  3. Obyek PQconn aman utas

  4. Cara mengakses Oracle Database di PostgreSQL

  5. Buat skema jika tidak ada dengan menggunakan spring Jpa dengan hibernate