0

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

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;
4

1 回答 1

0

改为使用coalescesum

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;
于 2017-04-01T17:22:04.650 回答