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

Update field to zero in one table when data for the respective field is not present in the other table in sqlite

我正在使用 SQLite。下面显示了两个 table。

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)

基于 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的记录必须是负数(贷方-借方=>其中贷方必须取零因为没有信用记录。)。

怎么做?

假设有一个 table names 列出所有名字(否则 efg 从哪里冲刺出来?!),然后像...:[=​​14=]

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

创建并填充 table 并检查主要的,然后

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

看起来大致是你想要的,对吧?