sql >> データベース >  >> RDS >> PostgreSQL

内部参加のカウントとすべてのアイテムのカウントを取得するにはどうすればよいですか?

    2つのクエリをユニオン互換にすると、結果を組み合わせて、追加のクエリで集計できます。

        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
    

    0 AS "total_accounts"を持つ および0 AS "churned_accounts" 2つのクエリに同じフィールドが存在することを意味します。これによりUNION 可能です。




    1. 結果を日付で並べ替えてグループ化

    2. MySQL EXPLAINの出力を解釈する方法は?

    3. MySQLの条件付き並べ替え?

    4. 複数のテーブルを参照する外部キー