Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
SQL cumulative sums
Message
From
26/06/2019 10:23:59
 
 
To
26/06/2019 09:44:05
General information
Forum:
Visual FoxPro
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
01669299
Message ID:
01669302
Views:
62
Likes (1)
>Is there a way to have a cumulative field in a SQL expression?
>
>If I had three records:
>
CREATE CURSOR t1 (cDesc c(10), nValue i)
>INSERT INTO t1 VALUES("Record 1", 10)
>INSERT INTO t1 VALUES("Record 2", 15)
>INSERT INTO t1 VALUES("Record 3", 7)
>
>SELECT cDesc, nValue, CUMULATIVE(nValue) as nCumulative ;
>    FROM t1 ;
>    ORDER BY 1 ;
>    INTO CURSOR t2
>
>BROWSE LAST NOWAIT
>* Should produce a data set:
>*     Record 1, 10, 10
>*     Record 2, 15, 25
>*     Record 3,  7, 32
>
Rick,

First, you must set the order of the records. RECNO() won't work with multi-from SQL statements.

That said...
CREATE CURSOR t1 (RecOrder Int AutoInc, cDesc c(10), nValue i)
INSERT INTO t1 (cDesc, nValue) VALUES("Record 1", 10)
INSERT INTO t1 (cDesc, nValue) VALUES("Record 2", 15)
INSERT INTO t1 (cDesc, nValue) VALUES("Record 3", 7)

SELECT t1.RecOrder, t1.cDesc, t1.nValue, ;
		t1.nvalue + NVL(t2.Accumulated, 0) AS PostAccumulated, ;
		NVL(t2.Accumulated, 0) AS PreAccumulated ;
	FROM t1 ;
		LEFT JOIN ;
			(SELECT t1x.recorder, SUM(t2x.nValue) AS Accumulated ;
				FROM t1 AS t1x INNER JOIN t1 AS t2x ON t2x.recorder < t1x.recorder ;
				GROUP BY t1x.recorder) t2 ON t2.RecOrder = t1.RecOrder
(maybe there is some room for simplification, but that what's popped up in a couple of minutes).
----------------------------------
António Tavares Lopes
Previous
Reply
Map
View

Click here to load this message in the networking platform