sql >> Database teknologi >  >> RDS >> PostgreSQL

Hvordan får man tælling af INNER join og tælling af tælling af alle varer?

Hvis du gør dine to forespørgsler Union-kompatible, kan du kombinere resultaterne og samle med en ekstra forespørgsel:

    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

At have 0 AS "total_accounts" og 0 AS "churned_accounts" betyder, at de to forespørgsler har de samme felter til stede, hvilket gør UNION muligt.




  1. Bulk C#-datatabel til postgresql-tabel

  2. Hvordan kan jeg registrere, om den tilsluttede database er MariaDB eller MySQL?

  3. problem med GROUP_CONCAT i JOIN-forespørgsel mysql

  4. mysql-connector-java-8.0.12:får fejl for 'Malay Peninsula Standard Time' server tidszone