我有一个带有列(a,b)的表A和一个带有列(b,c)的表B.我想做以下事情:
STEP 1: do a A LEFT OUTER JOIN B ON A.b = B.b
STEP 2: convert all c = NULL in the Joined table to c = <default_value>
STEP 3: SUM(A.a * B.c) over the table I get after STEP 2
在一个复合语句中有快速的方法吗?
谢谢!
答案 0 :(得分:1)
您可以在一个查询中执行这三个步骤,首先LEFT OUTER JOIN
并使用IFNULL
将NULL
值设置为默认值,然后使用SUM
:
SELECT
SUM(A.a + IFNULL(B.c, <default_value>))
FROM A
LEFT OUTER JOIN B ON A.b = B.b;
SQL小提琴演示:
答案 1 :(得分:0)
select
sum(A.a + IFNULL(B.c, some_default)) as some_sum
FROM
A
LEFT JOIN B
ON
B.b = A.b
答案 2 :(得分:0)
select sum(A.a * (case when B.c = null then <default> else B.c end)) as joined_sum
from A left outer join B on (A.b = B.b);