我有两个表(输入和类别):

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

我需要从每个类别的inputs表中获取sums(dvalue列)。即使和的结果是零。
如果有可能的话,我最好能得到每个父类别的总和(当categories.iId = categories.iParent时,将子类别的结果相加为父类别)
有人能帮我吗?谢谢你的帮助!
谢谢!

最佳答案

试试这个:

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

09-30 09:04