PostgreSQL如何将列的数值与另一个数值的SUM进行比较?

时间:2016-04-20 20:09:05

标签: sql database postgresql

我是PostgreSQL的新手并恢复了这个数据库,以便练习我的查询。它包含以下表格:

enter image description here

查找order_total少于line_total总和的订单数量的最佳查询是什么?

这是我的查询,但我怀疑我的号码是否准确。我觉得我做错了什么:

select COUNT(order_total) from orders
join order_lines
on orders.id = order_lines.order_id
having count(order_total) < sum(line_total)

我是否正确查询?

由于

2 个答案:

答案 0 :(得分:1)

也许是这样的

select o.order_total,sum( l.line_total) as sum_line_total
from orders o join order_lines l on o.orders.id=l.order_id
group by o.order_total
having o.order_total < sum(l.line_total)

答案 1 :(得分:0)

答案给出了不止一个结果。我通过使用以下子查询进行了实验并得出了正确的答案:

select count(*) from orders,
(Select order_id, sum(line_total) from order_lines group by order_id) a
where order_total < a.sum and order_id = orders.id;

感谢您的回复

相关问题