Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtered running sum view in SQLite

I have an append-only Operation table with the following columns:

  • Id, INTEGER, primary key, auto-incremented
  • LotId, INTEGER, foreign key, auto-incremented
  • Amount, INTEGER

Whenever there is a new row inserted in this table I need the balance to be reflected, so I created a Ledger view with:

CREATE VIEW IF NOT EXISTS "Ledger" ("OperationId", "Balance") 
AS SELECT "Id", SUM("Amount") OVER (ROWS UNBOUNDED PRECEDING) 
FROM "Operation";

What I need is further filtering of the running sum by LotId, that is the sum should only include those rows from Operation where the LotId matches.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example

Operation                  Ledger

Id | LotId |Amount         OperationId | LotId | Balance
---+-------+------         ------------+-------+--------
1  | 1     | 10            1           | 1     | 10
2  | 2     | 5             2           | 2     | 5
3  | 1     | -7            3           | 1     | 3

>Solution :

You should use the PARTITION BY clause to get the sums by LotId:

CREATE VIEW IF NOT EXISTS Ledger AS 
SELECT Id AS OperationId, 
       LotId,
       SUM(Amount) OVER (PARTITION BY LotId ORDER BY Id) AS Balance
FROM Operation;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading