简体   繁体   中英

SQL. Comparing value from current row versus the value resulted from the same comparison of the previous row

I am trying to create a script that would compare and get the higher value from current row versus the value resulted from the same comparison of the previous row.

样品表

For example:

  1. Row 2 Column 'Given' > Row 5 Column 'Result'. Therefore, Row 2 Column 'Result' gets the same value in Row 2 Column 'Given'

  2. Row 3 Column 'Given' < Row 2 Column 'Result'. Therefore, we will retain the value in Row 2 Column 'Result'. Same Thing with Row 4

  3. Rpw 5 Column 'Given' is now > Row 4 Column 'Result'. Therefore we will get the value in Row 5 Column.

My problem is it needs to be referenced on the same field that is yet to be created. Do you know any steps on how to attack this problem? Thank you!

It seems that you are looking for something like this:

DECLARE @DataSource TABLE
(
    [RowID] INT
   ,[given] INT
);

INSERT INTO @DataSource ([RowID], [given])
VALUES (1, 10)
      ,(2, 15)
      ,(3, 12)
      ,(4, 14)
      ,(5, 20);

SELECT [given]
      ,MAX([given]) OVER (ORDER BY [RowID])
FROM @DataSource;

在此处输入图片说明

You can check the OVER clause as you may need to use PARTITION BY or ROWS BETWEEN in your real case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM