我有两个表(输入和类别):
CREATE TABLE categories (
iId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
sName TEXT NOT NULL,
iParent INTEGER,
FOREIGN KEY (iParent) REFERENCES categories(iId)
);
CREATE TABLE inputs (
iId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
iCategory INTEGER,
dValue DOUBLE NOT NULL,
FOREIGN KEY (iCategory) REFERENCES categories(iId)
);
我需要从每个类别的输入表中获取总和(dValue列)。即使总和结果为零。
如果可以获得每个父类别的总和(当categories.iId = categories.iParent
时,将子类别的结果与父类别相加)可能会更好
任何人都可以帮助我吗?我感谢任何帮助! 谢谢!
答案 0 :(得分:3)
试试这个:
select c.iParent, sum(i.dValue)
from categories c
left outer join inputs i on i.iCategory=c.iId
group by c.iParent
编辑:使用帐户:
select c.iParent, a.iCurrency, sum(i.dValue)
from categories c
left outer join inputs i on i.iCategory=c.iId
left outer join accounts a on i.iAccount=a.iId
group by c.iParent,a.iCurrency