How do I get a column that is the sum of all the values before of another column?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
If you have a version of SQLite that doesn't support OVER here is another approach using recursion against a group_concat string of rows.
On SQLite version 3.22.0 2018-01-22 18:45:57 group_concat returns rows in database order. Create a common table expression and order it for different orders as in table work1 in the example.
You can do it by joining the table with itself (performing a so-called Cartesian or cross join). See the following example.
Given a table containing countries and their per capita GDP it will give you a running total of the GDP figure.
Note that this can be a very resource-intensive operation, because if a table has N elements it will create a temporary table with N*N elements. I would not perform it on a large table.
You have to do a sum in the field you want.... The query depends on the database you're using, Oracle allows you to do this:
Cross join solutions like Diomidis Spinellis suggested take O(N^2) time. A recursive CTE can work faster, if you can stomach the convoluted code.
This produces the same output as his.
Ordering and comparisons take care of duplicates,
COALESCE
is there to ignore NULLs.If you have a good index, this should be O(N log N). Since SQLite doesn't support cursors, an O(N) solution probably doesn't exist without relying on an external application.
As of SQLite 3.25.0, since 2018-09-15, window functions and their keyword
OVER
are supported. The answer to your question is now easy:This is the minimal query that does what you request, but it doesn't define any ordering so here is a more proper way of doing it.
In any way, the query should run in O(N) time.