gpt4 book ai didi

sql - PostgreSQL LEFT JOIN 无法正常工作

转载 作者:行者123 更新时间:2023-11-29 11:23:29 25 4
gpt4 key购买 nike

我有 2 个表:

T1 (id, flag1)
T2 (id, amount, date, flag2, t1_id);

我有以下查询:

SELECT T1.id, ROUND(COALESCE(SUM(T2.amount), 0), 2) AS spent_amount
FROM T1
LEFT JOIN T2 ON T2.t1_id = T1.id
WHERE T2.date <= '2014-01-01' AND T2.flag2 = 't' AND T1.flag1 = 't'
GROUP BY T1.id

问题是我想在结果中有一行,例如:id = 123, spent_amount = 0 以防我在 T1 中有一个入口,但它在 T2 中没有连接的行。

最佳答案

在您的 T2 上有一个 WHERE 子句,它将过滤掉所有 NULLS:

SELECT T1.id, ROUND(COALESCE(SUM(T2.amount), 0), 2) AS spent_amount 
FROM T1
LEFT JOIN T2
ON T2.t1_id = T1.id
AND T2.date <= '2014-01-01'
AND T2.flag2 = 't'
WHERE T1.flag1 = 't'

关于sql - PostgreSQL LEFT JOIN 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com