Trying to query difference between rows in table

Long story short in an old 7.8.5 system.

I have a table where I query to populate. I want to get a difference between each row.

Lets say

row 1
row 2

i could have a column that = row 2 - row 1 is x

Here is my current code minus that additional col.

SELECT wastewaterlog.t_stamp AS Date_And_Time,
  wastewaterlog.GrandTotal AS Totalizer_Read_Gallons,
  wastewaterlog.FlowRate / 10 AS Flow_Rate_GPM
FROM wastewaterlog
WHERE wastewaterlog.t_stamp BETWEEN "{Root Container.Start Date.text} 00:00:00" AND "{Root Container.End Date.text} 23:59:59"

i basically want to check totalizer read gallos and indicate how many gallons were added each row.

This is a job for window functions, like lead and lag. What db flavor are you using?

Tried lag and got an error. using MySQL 5.1

Got this code to work. But it takes a little bit to load. Any idea how I can speed it up?

SELECT 
    main.t_stamp AS Date_And_Time,  
    main.GrandTotal AS Totalizer_Read_Gallons,  
    main.FlowRate / 10 AS Flow_Rate_GPM,
    main.GrandTotal - IFNULL((SELECT sub.GrandTotal 
                             FROM wastewaterlog sub 
                             WHERE sub.t_stamp < main.t_stamp 
                             ORDER BY sub.t_stamp DESC 
                             LIMIT 1), main.GrandTotal) AS Gallons_Change
FROM wastewaterlog main
WHERE main.t_stamp BETWEEN "{Root Container.Start Date.text} 00:00:00" AND "{Root Container.End Date.text} 23:59:59"
ORDER BY main.t_stamp;

SELECT 
	t_stamp AS Date_And_Time,
	GrandTotal AS Totalizer_Read_Gallons,
	GrandTotal - LAG(GrandTotal) OVER (ORDER BY t_stamp) AS diff,
	FlowRate / 10 AS Flow_Rate_GPM
FROM 
	wastewaterlog
WHERE
...
1 Like

missing the change gallons in that edit. Just want to verify do I insert that?

I named it diff on a whim, so you can just change it to Gallons_Change

Gave me an error, gotta hit they hay, i'll upload it in a little.

Looks like the window functions in MySQL weren't added until version 8.0. Can you upgrade it?

Negative.

I'd probably create a Stored Procedure in the DB and just call it from Ignition.

SQL Stored Procedures | Ignition User Manual