0

I need to compare grouped data to look for shifts in a calculated value. The output of my current SQL looks something like this...

Grp_ID_1 / Metric / State / Value
A   Metric1 OH  50
B   Metric1 OH  65
A   Metric1 CA  20
B   Metric1 CA  35

In the example above, I need to calculate the difference between A-Metric1-OH value of 50 and B-metric1-OH value of 65.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Mike
  • 85
  • 8
  • lookup how to PIVOT – T McKeown Oct 04 '18 at 17:30
  • doing a little research, it appears that I have to define every column in pivot. For this particular example, I would need to list all 50 states. Other comparisons are even more complex. This seems inefficient. Need a way to simply state the subgroups (metric/state) and then compare across the two groupIDs. Will always have 2 groups, base/test sort of scenario. – Mike Oct 04 '18 at 18:13

2 Answers2

0

You can use LEAD to calculate difference between rows.

SELECT LEAD(State, 1,0) OVER (ORDER BY Grp_ID_1 ) AS NextState ,
State - LEAD(State, 1,0) OVER (ORDER BY Grp_ID_1 ) AS StateDif
FROM yourTable 
Eugene
  • 1,487
  • 10
  • 23
0
        SELECT  grp_ID_1, metric, state, value,       
                (SELECT  MAX(value) 
                    FROM tablename   
                 ) - value AS Difference

        FROM tablename  group by state, grp_ID_1, metric, value  
        having state = 'OH' 
lije
  • 420
  • 2
  • 15
  • 1
    Welcome to Stack Overflow! You may want to improve your answer by making it less tentative (don't use "try this") and adding a short explanation of the crucial part. For future readers it's not clear if a suggestion to try something was helpful or not. – Gert Arnold Oct 04 '18 at 20:26