【发布时间】:2020-11-10 21:19:37
【问题描述】:
我仍然是学习 PSQL 的新手,想知道如何 LEFT JOIN 我从同一个物化视图中检索的两个单独的查询。
这是我的第一个查询:
select rep_name, Count(enroll_date) new_orders, Sum(invoice_total) contract_total, Avg(invoice_total) avg_contract_total
from recent_billing_mat_view
where
enroll_date <= current_date
AND enroll_date > (current_date - '30 days'::interval)
AND product_type = 'CTF'
AND pay_type <> 'Credit'
group by rep_name
它返回以下内容:
rep_name new_orders contract_total avg_contract_total
"Alyssa" 9 2515 279.444444444444
"Carlos" 24 6585 274.375
"Cheryle" 14 4871 347.928571428571
"Nicholas" 19 4775 251.315789473684
"Piero" 13 4405.5 338.884615384615
"Susan" 15 4450.5 296.7
"Valerie" 16 4640 290
"Yelitza" 12 3607 300.583333333333
这是我的第二个查询:
select rep_name, Count(enroll_date) orders_paid
from recent_billing_mat_view
where
enroll_date <= current_date
AND enroll_date > (current_date - '30 days'::interval)
AND product_type = 'CTF'
AND pay_type <> 'Credit'
AND amount_paid > 0
group by rep_name
它返回以下内容:
rep_name orders_paid
"Alyssa" 6
"Carlos" 16
"Cheryle" 8
"Nicholas" 14
"Piero" 9
"Susan" 8
"Valerie" 10
"Yelitza" 9
我正在使用第二个查询来获取为每个代表支付的所有订单的计数,并且我想在第一个查询中加入它。我目前收到错误:错误:“LEFT”或附近的语法错误。
这是我正在使用的:
select r.rep_name, Count(enroll_date) new_orders, Sum(invoice_total) contract_total, Avg(invoice_total) avg_contract_total
from recent_billing_mat_view r
where
r.enroll_date <= current_date
AND r.enroll_date > (current_date - '30 days'::interval)
AND r.product_type = 'CTF'
AND r.pay_type <> 'Credit'
group by r.rep_name
LEFT JOIN (
select Count(enroll_date) orders_paid
from recent_billing_mat_view p
where
p.enroll_date <= current_date
AND p.enroll_date > (current_date - '30 days'::interval)
AND p.product_type = 'CTF'
AND p.pay_type <> 'Credit'
AND p.amount_paid > 0
group by rep_name
) as p On r.rep_name = p.rep_name
我希望结果是什么样的:
rep_name new_orders contract_total avg_contract_total orders_paid
"Alyssa" 9 2515 279.444444444444 6
"Carlos" 24 6585 274.375 16
"Cheryle" 14 4871 347.928571428571 8
"Nicholas" 19 4775 251.315789473684 14
"Piero" 13 4405.5 338.884615384615 9
"Susan" 15 4450.5 296.7 8
"Valerie" 16 4640 290 10
"Yelitza" 12 3607 300.583333333333 9
我在这里缺少什么?没有 LEFT JOIN 有没有更好的方法来做到这一点?
谢谢!
【问题讨论】:
标签: sql postgresql count sum aggregate-functions