2014-09-03 72 views
0

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. 
+0

你可以创建到SQL小提琴? – 2014-09-03 15:24:37

+0

提供预期结果的示例。 – 2014-09-03 15:25:19

+0

我很抱歉我的无知,但是什么是小提琴? – OJVM 2014-09-03 15:30:56

回答

2

试试这个:

SELECT A.ID, B.ID, C.ResultSum 
FROM TableA A 
LEFT JOIN TableB B ON (B.FK = A.ID) 
LEFT JOIN ( 
    SELECT FK, SUM(Amount * Price) AS ResultSum 
    FROM TableC 
    GROUP BY FK 
) C ON (C.FK = B.ID) AND (ResultSum > 0) 

见演示here

+0

这里有一个示例[SQL Fiddle](http://www.sqlfiddle.com/#!1/f482a/2)供您查询。 – jpw 2014-09-03 15:59:26

+0

谢谢@Ruslan Veselov这工作得很好。 – OJVM 2014-09-03 16:38:13