2014-09-03 41 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