SELECT
t.id,
sum(o.amount),
t.parent_id
FROM tab t
LEFT JOIN order o ON o.deal = t.id
GROUP BY t.id
电流输出:
既定的输出:
with the_data(id, sum, parent_id) as (
values
(1, 10, null),
(2, 10, null),
(3, 15, 5),
(4, 30, 5),
(5, 0, null),
(6, 0, 8),
(7, 0, 8),
(8, 20, null)
)
select coalesce(parent_id, id) as id, sum(sum)
from the_data
group by 1
order by 1
在文档中阅读有关该功能的信息。 db<>fiddle. 您的查询在postgresql中无效:
SELECT
t.id,
sum(o.amount),
t.parent_id
FROM tab t
LEFT JOIN order o ON o.deal = t.id
GROUP BY t.id
GROUP BY
子句中使用
t.id
,则每个
GROUP BY
将产生一行,因此您始终将3和4分开。
看起来您正在尝试将
t.id
用作分组的主要标准,当parent_id
是
id
时倒在
parent_id
时。您可以使用
NULL
来获取每一行的值,然后使用它进行分组。
例如:
COALESCE(t.parent_id, t.id)