Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite SUM() between several rows

I need some help with the SUM feature in android app. I have a table that looks something like the following :

enter image description here

I have need to SUM Quantities between last two records Notes and last one record with Note. I need to sum Quantity of rows 31,32 and 33. It would return 90. I've tried

SELECT Sum(QUANTITY) FROM fuel_table WHERE NOTE!='' ORDER BY ID DESC

but it returns SUM of all quantities with note.

like image 335
Simeon Shopkin Avatar asked Dec 29 '15 14:12

Simeon Shopkin


People also ask

How do I sum multiple rows in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. The syntax of the SUM() function is as follows: SUM([ALL | DISTINCT ] expression) In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates.

How do I sum individual rows in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do I sum a row in SQLite?

In SQLite SUM() Function is an aggregate function which is used to calculate the sum of values in a specified expression or column. Generally, in SQLite SUM() function will work with non-NULL numeric values to return the summed values of a column in a table.

How can I sum rows with same ID in SQL?

To sum rows with same ID, use the GROUP BY HAVING clause.


1 Answers

I am inclined to phrase the question as: sum the quantity from all rows that have one note "ahead" of them. This suggests:

select sum(quantity)
from (select ft.*,
             (select count(*)
              from fuel_table ft2
              where ft2.note = 'Yes' and ft2.id >= ft.id
             ) as numNotesAhead
      from fuel_table ft
     ) ft
where numNotesAhead = 1;
like image 93
Gordon Linoff Avatar answered Sep 23 '22 04:09

Gordon Linoff