我目前有三个查询,我想将其合而为一。这是三个。
TotalDistinctUsers NonpayingUsers PayingUsers
3 2 1
第一个查询是找到之前没有付款的用户,第二个查询是至少支付一次的,第三个是数据库中所有电子邮件的计数。
是否可以将它们合二为一?感谢
EDIT 最终的结果应该给我一个像这样的表
id email payment item
1 abc@123.com paid newspaper
2 def@123.com unpaid magazine
3 ghi@123.com unpaid books
4 abc@123.com unpaid books
当前表格结构
{{1}}
答案 0 :(得分:3)
涉及黑客但我认为它可以解决您的问题。尝试一次,如果有效,我会向你解释我做了什么:
Select NonPayingusers, PayingUsers, TotalDistinctUsers FROM
(SELECT count(Distinct Email) as NonpayingUsers, 0 as id FROM table GROUP BY Email
having (sum(payment = 'paid')) = 0)t1
left join(
SELECT count(DISTINCT Email) as PayingUsers, 0 as id from table WHERE payment='paid'
)t2 on t1.id =t2.id
left join(
SELECT count(DISTINCT Email) as TotalDistinctUsers, 0 as id from table
)t3 on t2.id =t3.id
这里" t1,t2和t3"是带有虚拟列的临时表" id"添加到每个表中,以便它们可以在该列上连接。