SQLITE:显示每个类别的总计(总和)

时间:2012-06-04 14:05:58

标签: sql database sqlite

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

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时,将子类别的结果与父类别相加)可能会更好

任何人都可以帮助我吗?我感谢任何帮助! 谢谢!

1 个答案:

答案 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