我有两个表,paid_users和paid_users_no还有更多。从本质上讲,付费用户可以拥有多个帐户。
他们的模式如下:
paid_users:
payor_id | user_email | payor_email | payment_start_date
---------------------------------------------------------
| | |
paid_users_no_more:
user_id | payment_stop_date
---------------------------
|
我写了一个查询来获取用于支付哪些帐户以及在给定月份中哪些帐户不再支付(流失的帐户):
SELECT payor_id, count(*) as "churned 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;
这为我提供了8月份每个payor_id的流失帐户数量 - 我如何获取付款人拥有的帐户总数?即,以下查询为我提供了每个payor_id的帐户数量:
SELECT paid_users.payor_email,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;
我希望能够以某种方式加入两个结果表来查看"搅拌帐户"和"总帐户" (因为我想计算流失的收入,而且会有更多的帐户,它们的成本会越便宜) - 有没有办法加入这些表?
谢谢!
答案 0 :(得分:1)
如果您使两个查询Union Compatible,那么您可以将结果和聚合与其他查询结合起来:
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"
表示两个查询具有相同的字段,这使UNION
成为可能。