Quantcast
Viewing all articles
Browse latest Browse all 207

How to order by cumulative value?

In my application widgets move step by step through a workflow. I want to list the widgets ordered by their step due-dates but I can't figure out how to do that.

There are many workflows. Each workflow has a number of steps ordered by integer position. Each step has an integer duration for the number of days it should take.

A widget has a start date and points to its current step in a workflow. To calculate a step's due date, I add up the durations of the steps (in the same workflow) which preceded it, add on the step's own duration, and add the total to the widget's start date.

I can't figure out how to express this in SQL. I suspect window functions or common table expressions are involved but I don't have any experience with them.

The simplified tables look like:

workflows: idsteps: id, workflow_id, position, durationwidgets: id, start_date, step_id

Conceptually for each widget I want to calculate the cumulative duration for its step in the step's workflow and add that to the widget's start date.

To just calculate the cumulative duration for each step I can do this:

WITH f AS (  SELECT p.id, sum(q.duration) AS tot  FROM steps p  INNER JOIN steps q  ON p.workflow_id=q.workflow_id AND q.position<=p.position  GROUP BY p.id)SELECT w.id, w.step_id, f.totFROM widgets wINNER JOIN fON f.id=w.step_id;

I just need to figure out how to add these total durations to the start dates and order by them.


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>