PostgreSQL的9.1 我有一个查询,必须返回只有当聚合函数SUMPostgreSQL的查询与左连接,并具有
两个领域的是大于零的第二个表的值。这是数据。
table a
id
1
2
3
table b
id fk(table a)
1 1
2 null
3 3
table c
id fk(table b) amount price
1 1 1 10 --positive
2 1 1 -10 --negative
3 3 2 5
正如你所看到的,表B有一些IDS从表,并表C可以有1个或多个引用表B, 表c只有在总和(金额*价格)> 0时才被检索。 我写了这个查询。
select a.id, b.id, SUM(c.amount * c.price) amount from tablea a
LEFT JOIN tableb b ON b.fk = a.id
LEFT JOIN tablec c on c.fk = b.id
GROUP BY a.id, b.id
HAVING SUM(c.amount * c.price) > 0
但这个查询没有从表只是行1检索所有行,我需要两行。我知道这是因为条款HAVING子句,但我不知道如何重写它。
谢谢。
编辑
spected结果
a b sum
1 null null -- the sum of 1 * 10 (rows 1 and two) = 0 so its not retived.
2 null null -- no foreing key in second table
3 3 10 -- the sum of 2 * 5 (row 3) > 0 so it's ok.
你可以创建到SQL小提琴? – 2014-09-03 15:24:37
提供预期结果的示例。 – 2014-09-03 15:25:19
我很抱歉我的无知,但是什么是小提琴? – OJVM 2014-09-03 15:30:56