Link to home
Start Free TrialLog in
Avatar of ukerandi
ukerandiFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Maths - Delta Query

Hi
I need to find this number series Total Delta
25,      24,      24,      25,      25

My answer is 0, i just wondering is correct or not.
24-25= -1
24-24  = 0
25-24 = 1
25-25 =0

After Add all together to find Delta i got = 0
Avatar of Sean Stuber
Sean Stuber

Not sure exactly why you want it as sql but it's fairly easy to do....


WITH yourdata
     AS (SELECT 1 id, 25 n FROM DUAL
         UNION ALL
         SELECT 2, 24 FROM DUAL
         UNION ALL
         SELECT 3, 24 FROM DUAL
         UNION ALL
         SELECT 4, 25 FROM DUAL
         UNION ALL
         SELECT 5, 25 FROM DUAL)
SELECT SUM(diff)
  FROM (SELECT n - LAG(n) OVER (ORDER BY id) diff FROM yourdata);



Assuming your data is in a table somewhere, simply remove the WITH clause and change yourdata to your table and the other columns as appropriate
Avatar of ukerandi

ASKER

Thanks, But i need Answer for that my formula
Delta means - It is just the difference between any two values.
I know what a delta is

n - LAG(n) OVER (ORDER BY id)   --- there's your delta

but you asked for the sum of them   so sum in the outer query

and that's 0
so that mean my answer is correct?
yes

A variant on that sql that displays the details; the "LAG(N)OVER(ORDERBYID)" column is the n of the previous row.
The column "DIFF" when summed = 0

| LAG(N)OVER(ORDERBYID) |  N |   DIFF |
|-----------------------|----|--------|
|                (null) | 25 | (null) |
|                    25 | 24 |     -1 |
|                    24 | 24 |      0 |
|                    24 | 25 |      1 |
|                    25 | 25 |      0 |

WITH yourdata
      AS (
         SELECT 1 id, 25 n FROM DUAL
         UNION ALL
         SELECT 2, 24 FROM DUAL
         UNION ALL
         SELECT 3, 24 FROM DUAL
         UNION ALL
         SELECT 4, 25 FROM DUAL
         UNION ALL
         SELECT 5, 25 FROM DUAL
            )
SELECT
      LAG(n) OVER (ORDER BY id)
    , n
    , n - LAG(n) OVER (ORDER BY id) diff
FROM yourdata
;

http://sqlfiddle.com/#!4/d41d8/33755

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Sean Stuber
Sean Stuber

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial