1

Suppose i have a column C in a table T, which is as follow:

sr c
1 34444444444440
2 34444444444442
3 34444444444444
4 34444444444446
5 34444444444448
6 34444444444450

How can i verify or check if the values in Column C are arithmetic progression?

3 Answers3

2

An arithmetic progression means that the differences are all constants. Assuming that the values are not floating point, then you can directly compare them:

select (min(c - prev_c) = max(c - prev_c)) as is_arithmetic_progression
from (select t.*,
             lag(c) over (order by sr) as prev_c
      from t
     ) t

If these are floating point values, you probably want some sort of tolerance, such as:

select abs(min(c - prev_c), max(c - prev_c)) < 0.001 as is_arithmetic_progression
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

step-by-step demo:db<>fiddle

SELECT
    COUNT(*) = 1 as is_arithmetic_progression             -- 4
FROM (
    SELECT
        difference
    FROM (
        SELECT
            *,
            lead(c) OVER (ORDER BY sr) - c as difference  -- 1
        FROM
            mytable
    ) s
    WHERE difference IS NOT NULL                          -- 2
    GROUP BY difference                                   -- 3
) s

Arithmetical progression: The difference between each element is constant.

  1. lead() window function shifts the next value into the current row. Generating the difference to the current value shows the difference
  2. lead() creates a NULL value in the last column, because it has no "next" value. So, this will be filtered
  3. Grouping the difference values.
  4. If you only have one difference value, this would return in only one single group. Only one difference value means: You have a constant difference between the elements. That is exactly what arithmetical progression means. So if the number of groups is exactly 1, you have arithmetical progression.
S-Man
  • 22,521
  • 7
  • 40
  • 63
  • have you seen the last value - `344444444444410` which is more higher than other values. Your query will give result in false for given sample data – Popeye Jan 13 '21 at 09:27
  • @Popeye Yes, as wrote in the comments above, the example is NO arithmetic progression because of this value. I guess, it's a mistake of the TO. The value must be 34444444444450 to be an arith. progression – S-Man Jan 13 '21 at 09:40
-1

You can use exists as follows:

Select case when count(*) > 0 then 'no progression' else 'progression' end as res_
  From your_table t
 Where exists
      (select 1 from your_table tt
        Where tt.str > t.str
          And tt.c < t.c)
Popeye
  • 35,427
  • 4
  • 10
  • 31
  • https://en.wikipedia.org/wiki/Arithmetic_progression Arithmetical progression means that the difference between all elements is constant. You check for increasing values, but not if the values are increasing constantly – S-Man Jan 13 '21 at 09:04