0

I have a problem with transferring an Excel formula to SQL. My excel formula is: =IF(P2<(MAX($P$2:P2));"Move";""). The P column in excel is a sequence of numbers.

a | b 
------
1   
2   
7   
3   MOVE
4   MOVE
8   
9
5   MOVE
10

You can find more example on this screenshot:

Excel screenshot

I created a cursor with a loop but I don't know how to check max from range. For example when I iterate for fourth row, I have to check max from 1-4 row etc.

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
anst
  • 21
  • 5

2 Answers2

1

No need for a cursor and a loop. Assuming that you have a column that defines the ordering of the rows (say, id), you can use window functions:

select t.*,
    case when a < max(a) over(order by id) then 'MOVE' end as b
from mytable t
GMB
  • 216,147
  • 25
  • 84
  • 135
0

One option would be using MAX() Analytic function . But in any case, you'd have an extra column such as id for ordering in order to determine the max value for the current row from the first row, since SQL statements represent unordered sets. If you have that id column with values ordered as in your sample data, then consider using

WITH t2 AS
(
SELECT MAX(a) OVER (ORDER BY id ROWS BETWEEN
                                UNBOUNDED PRECEDING
                                AND
                                CURRENT ROW) AS max_upto_this_row, 
       t.*
  FROM t
)
SELECT a, CASE WHEN max_upto_this_row > a THEN 'Move' END AS b
  FROM t2
 ORDER BY id;

Demo

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55