简体   繁体   中英

Android Sum Quantity values from two Columns in two tables and update the Quantity value in one of the Column with the summed value

I have two tables, Table A and Table B with Columns Qty_A and Qty_B

Table_A  
  Item_A1  Qty_A1      
  Item_A2  Qty_A2      


 Table_B
  Item_B1 Qty_B1      
  Item_B2 Qty_B2  

I want to run a query that will sum the Quantity values from both tables and update table A. So at the end of the Query, my Table_A will look like this

Table_A  
  Item_A1      Qty_A1 + Qty_B1   
  Item_B1      Qty_A2 + Qty_B2


this is what my Query attempt looks like
insert into Table_A (Qty_A)
select Qty_B sum(QTY_A + QTY_B)
from Table_B
where Item_A = Item_B and Date_A = Date('now')

You want to update table_a and not insert new rows:

update table_a 
set qty_a = qty_a + coalesce((
  select qty_b from table_b 
  where item_b = table_a.item_a), 0
)

See the demo . You have another condition in your code:

... and Date_A = Date('now')

which you don't mention earlier.
Maybe you can add it as it is in the above query, or if you want something else you must clarify.
Note that the above code will work only if there is only 1 match between the columns item_a and item_b . If there would exist more matches then changes must be done to the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM