postgresql SQL中的连接表没有返回所需的值

jfewjypa  于 2023-03-17  发布在  PostgreSQL
关注(0)|答案(2)|浏览(99)

我有两个类似Table:customersTable:orders的表,希望显示为join
我试过了

select 
concat(c.first_name, ' ', c.last_name) as customer_name,
COUNT(o.customer_id) as total_orders,
sum(o.amount) as total_amount_order
from customers c
join orders o on c.id = o.customer_id  
where o.amount >= 500
group by o.customer_id, c.first_name, c.last_name, o.amount

但是它只返回大卫数据。我的查询有什么问题吗?有什么建议吗?谢谢

dohp0rv5

dohp0rv51#

WHERE子句在GROUP BY子句之前执行,所以它在总计之前过滤掉了除了罗宾逊先生非常昂贵的监视器之外的所有购买。
我怀疑您想过滤SUM(o.amount) >= 500,但不能将其放在WHERE子句中,因为它们在聚合完成之前执行。
您需要使用HAVING子句,该子句与WHERE相同,但在聚合之后执行,从而允许您执行HAVING SUM(o.amount) >= 500
我本想给你看更新后的查询,但我感觉这是家庭作业。)

dw1jzc5e

dw1jzc5e2#

请试试这个

select 
concat(c.first_name, ' ', c.last_name) as customer_name,
COUNT(o.customer_id) as total_orders,
sum(o.amount) as total_amount_order
from customers c
join orders o on c.id = o.customer_id   
group by o.customer_id, c.first_name, c.last_name
having  sum(o.amount) >= 500

相关问题