当我LEFT JOIN 2表时,如果值为NULL,如何返回0?

时间:2017-04-01 17:20:44

标签: sqlite ionic2 ionic-native

我试图在SQLite中使用coalesce()或ifnull()在LEFT JOIN中将0设置为任何空值。 我知道这个问题已被问到很多,但是,我被困住了。

BUDGET
amount category
2      food
2      book
2      movie

EXPENSE
amount category
2      food
2      book

EXPECTED RESULT
budsum budcat expsum
2      food   2
2      book   2
2      movie  0

这是我已经完成的查询。

SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum 
FROM budget 
LEFT JOIN expense 
ON budcat=expense.category
GROUP BY budcat;

SELECT SUM(budget.amount) AS budsum, budget.category AS budcat,
SUM(coalesce(expense.amount,0)) AS expsum 
FROM budget 
LEFT JOIN expense 
ON budcat=expense.category
GROUP BY budcat;

1 个答案:

答案 0 :(得分:0)

使用coalesce代替sum

select SUM(budget.amount) as budsum,
    budget.category as budcat,
    coalesce(SUM(expense.amount), 0) as expsum
from budget
left join expense on budget.category = expense.category
group by budget.category;