How to calculate the total under recursive relationships with esProc

A certain database has a ticket table and a work hour table. The ticket table stores the relationship between each ticket and its parent ticket, forming a self-association structure:

ticketid

parentID

1

6

2

7

3

8

4

9

5

10

6

18

7

19

8

20

9

21

10

22

11

23

12

18

13

19

14

20

15

21

16

22

17

23

18

24

19

25

20

26

21

27

22

28

23

29

24

30

25

30

26

30

27

30

28

30

29

30

30

0

30

0

The work hour table stores the direct working hours corresponding to each ticket:

ticketid

hours

0

4

1

3

2

6

3

9

4

11

5

5

6

10

7

9

8

11

9

7

10

13

11

2

12

10

13

4

14

9

15

14

16

8

17

8

18

7

19

9

20

9

21

8

22

12

23

14

24

13

25

9

26

12

27

5

28

10

29

5

30

0

Now we need to recursively calculate the total working hours, which is the sum of the direct working hours of each ticket and the working hours of all subordinate sub tickets.

ticketid

Total_hours

1

3

2

6

3

9

4

11

5

5

6

13

7

15

8

20

9

18

10

18

11

2

12

10

13

4

14

9

15

14

16

8

17

8

18

30

19

28

20

38

21

40

22

38

23

24

24

43

25

37

26

50

27

45

28

48

29

29

30

252

SQL does not support references, makes it inconvenient to express self-associated relationships, lacks recursive functions, and makes code difficult to write. SPL provides reference functions and can establish self-associations; Provides recursive functions that can take all subordinate nodes: https://try.esproc.com/splx?4l2


 A

1

$select t.ticketid ticketid,t.parentID parentID,h.hours hours from tickets.txt t left join hours.txt h on t.ticketid=h.ticketid

2

>A1.switch(parentID,A1:ticketid)

3

=A1.new(ticketid,A1.nodes(parentID,~).sum(hours)+hours:Total_hours)

A1 Join two tables and load data.

A2 Use the switch function to modify the field values of the parent ticket to the record references of the parent ticket, and establish a self-associated relationship. Record references can intuitively express parent-child relationships. The following figure shows the parent tickets of all levels of ticket 3, [8,20,26,30].

Picture1png
A3=A1.new(A1.nodes(parentID,~)) Create a new two-dimensional table and first calculate all the subordinate records of the current record. The function nodes can recursively calculate all the subordinate records of a certain record, where ~ represents the current record. The following figure shows all subordinate records of ticket No. 26, [3,8,14,20]:

Picture2png
A3=A1.new(ticketid,A1.nodes(parentID,~).sum(hours)+hours:Total_hours) Then calculate the total working hours of the current ticket, which is the sum of the working hours of the subordinate sub tickets plus the direct working hours.

Picture3png