当sqlite中的另一个表中不存在相应字段的数据时,在一个表中将字段更新为零

时间:2015-02-14 13:03:10

标签: sqlite

我正在使用SQLite。有两个表格如下所示。

Transaction_Tbl
ID    Name    Credit/Debit    Value
1     ABC        credit        10
1     ABC        credit        10
2     DEF        credit        20
2     DEF        debit         40
(record for third employee EFG not present in the table)

根据该表,Emp_Tbl必须更新如下......

Emp_Table
ID    Name    Avg(Credit-Debit)
1     ABC     20
2     DEF     -20
3     EFG     0 (as no records for EFG in Transaction_Tbl)

现在,如果在Transaction_Tbl中存在用于借记的EFG记录,则在Emp_Tbl中,EFG的记录必须为负(信用 - 借记=>其中信用必须为零,因为没有信用记录。)。 / p>

怎么做?

1 个答案:

答案 0 :(得分:1)

假设有一个表names列出了所有名称(否则efg会从哪个地方冲出来?!),那么就像......:

sqlite> create table trans (id smallint, name string, cord string, value int);
sqlite> insert into trans(id,name,cord,value) values(1,'abc','credit',10);
sqlite> insert into trans(id,name,cord,value) values(1,'abc','credit',10);
sqlite> insert into trans(id,name,cord,value) values(2,'def','credit',20);
sqlite> insert into trans(id,name,cord,value) values(2,'def','debit',40);
sqlite> select * from trans;
1|abc|credit|10
1|abc|credit|10
2|def|credit|20
2|def|debit|40
sqlite> create table names (name string);
sqlite> insert into names(name) values('abc');
sqlite> insert into names(name) values('def');
sqlite> insert into names(name) values('efg');

创建并填充表并检查主表,然后

sqlite> select names.name, sum(case trans.cord when 'credit' then trans.value when 'debit' then -trans.value else 0 end) from names left outer join trans on names.name=trans.name group by names.name;
abc|20
def|-20
efg|0

看起来大概是你所追求的,对吧?