-2

Actually what i need was something like this : i have one row with so many columns, and my script should calculate the difference starting from the highest and the second highest, then 2nd highest and 3rd one.. it goes like that. Well Sql server can't even calculate the maximum value in a row ( it can calculate max in one column as i know ) So i used pivot for my table and now i have one column. I ordered them from max to lowest, now what i need is, how will i get the diffence :first value minus second value, second value minus third value...

cankut
  • 19
  • 7
  • 2
    code? tables? data? what have you tried? – gbn Jul 24 '17 at 09:18
  • imagine a table with one column,and many rows with specific numbers.Im new in forum sorry couldn't find a way to send my table to you.. – cankut Jul 24 '17 at 09:37
  • @cankut See: https://stackoverflow.com/help/how-to-ask & https://stackoverflow.com/help/mcve . Use http://sqlfiddle.com/ to provide a working example – Alex Jul 24 '17 at 09:52
  • This previous thread should give you your starting point https://stackoverflow.com/questions/710212/is-there-a-way-to-access-the-previous-row-value-in-a-select-statement – Helen Gore Jul 24 '17 at 11:39

1 Answers1

0

A couple of ways you can do this - and you should read up sql server analytic and window functions.

Given

DROP TABLE T

CREATE TABLE T (ID INT)
INSERT INTO T VALUES
(1),(10),(2),(5)

You could use the lag analytic function

SELECT ID ,
    LAG(ID, 1,0) OVER (ORDER BY ID DESC) LAGID,
    ID - LAG(ID, 1,0) OVER (ORDER BY ID DESC) DIFF
FROM T 

result

ID          LAGID       DIFF
----------- ----------- -----------
10          0           10
5           10          -5
2           5           -3
1           2           -1

(4 row(s) affected)

or using the row_number() window function

SELECT  TID,TRN,UID,URN, TID - UID AS DIFF
FROM
(
SELECT  T.ID TID 
        ,ROW_NUMBER() OVER (ORDER BY T.ID DESC) TRN
FROM T
) S
LEFT JOIN 
(SELECT  ID UID 
        ,ROW_NUMBER() OVER (ORDER BY ID DESC) URN
FROM T
) U
ON URN = TRN - 1

result

TID         TRN                  UID         URN                  DIFF
----------- -------------------- ----------- -------------------- -----------
10          1                    NULL        NULL                 NULL
5           2                    10          1                    -5
2           3                    5           2                    -3
1           4                    2           3                    -1

(4 row(s) affected)
P.Salmon
  • 17,104
  • 2
  • 12
  • 19
  • Well i have only 1 column, i need an alghoritm that gets the difference between each column starting from highest to lowest. Column ---------- 100 90 80 70 and the answer be like : Column ---------- 10 10 10 – cankut Jul 25 '17 at 08:09
  • Substitute lead for lag and trn + 1 for trn - 1 and read the manual. – P.Salmon Jul 25 '17 at 11:20