sqlite - Running Total example -


i have following data:

id  customer  date                value1  value2  istrue 10  13  2013-08-20 00:00:00.0000  170     180680  0 11  13  2013-09-02 00:00:00.0000  190     181830  0 12  13  2013-09-07 00:00:00.0000  150     183000  1 13  13  2013-09-14 00:00:00.0000  150     183930  0 14  13  2013-09-16 00:00:00.0000  150     184830  0 15  13  2013-09-19 00:00:00.0000  150     185765  1 16  13  2013-09-30 00:00:00.0000  800     187080  0 17  13  2013-10-02 00:00:00.0000  100     188210  0 28  13  2013-10-04 00:00:00.0000  380     188250  1 

how can have following results,where sumvalue1 summury of value1 until field istrue gets true , resets after , difference value2 difference of field value2 everytime istrue field gets true?

id  customer  date                value1  value2  istrue  sumvalue1  differencevalue2 10  13  2013-08-20 00:00:00.0000  170     180680  0 11  13  2013-09-02 00:00:00.0000  190     181830  0 12  13  2013-09-07 00:00:00.0000  150     183000  1       510        2320 13  13  2013-09-14 00:00:00.0000  150     183930  0 14  13  2013-09-16 00:00:00.0000  150     184830  0 15  13  2013-09-19 00:00:00.0000  150     185765  1       450        2765 16  13  2013-09-30 00:00:00.0000  800     187080  0 17  13  2013-10-02 00:00:00.0000  100     188210  0 28  13  2013-10-04 00:00:00.0000  380     188250  1       1280       2485 

assuming id ordering, query do:

select     id, customer, date, value1, value2, istrue,     case istrue when 1 (select total(value1) t customer=t2.customer , id>t2.prev_id , id<=t2.id) end sumvalue1,     case istrue when 1 value2-(select value2 t customer=t2.customer , id=t2.prev_id) end differencevalue2 (select *, case istrue when 1 coalesce((select id t _ customer=t.customer , date<t.date , istrue order date desc limit 1), -1) end prev_id t) t2; 

steps step:

previous id istrue given by:

select id t _ customer=t.customer , date<t.date , istrue order date desc limit 1 

using coalesce(..., -1) ensure non-null id before others (-1).

select *, case istrue when 1 ... end prev_id t return rows t column prev_id added.

at last, querying select total(value1) t customer=t2.customer , id>t2.prev_id , id<=t2.id , value2-(select value2 t customer=t2.customer , id=t2.prev_id on previous results return desired results.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -