Upsert in SQLite with running total if record is found

感情迁移 提交于 2019-12-02 19:36:08

问题


I would like to upsert data to a table in SQLite, but the column being updated (if the record is found) must be a running total. I am using a parameterized query, and am having trouble with the syntax.

My understanding thus far is that COALESCE is the way to do an upsert in SQLite, so this is the skeleton of what I've got thus far:

INSERT OR REPLACE INTO TABLE (ID, Quantity) 
VALUES (:ID, COALESCE(Quantity + :Quantity_change, :Quantity_change) 

In other words, if the record is found, add the quantity change to the current quantity, else insert the record with the quantity change as the quantity number.

In SQL server it's working perfectly with a merge query:

MERGE ......
.....
WHEN MATCHED THEN UPDATE SET Quantity = Quantity + :Quantity_change
WHEN NOT MATCHED THEN INSERT (..Quantity), VALUES (.. :Quantity_change); 

回答1:


OK so this is working for me:

INSERT OR REPLACE INTO TABLE (ID, Quantity) 
VALUES (:ID, 
        COALESCE(
          (SELECT Quantity FROM TABLE WHERE ID = :ID) + :Quantity_change, :Quantity_change));

Thanks to this SO link for the help.



来源:https://stackoverflow.com/questions/31429300/upsert-in-sqlite-with-running-total-if-record-is-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!