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