简体   繁体   中英

Difference between every 6th row in SQL

How I can calculate difference between every 6th row in SQL Server 2016? For example:

Col1     Col2   Diff
-----    ----   ----
1       2      NULL
2       4      NULL
3       6      NULL 
4       10     NULL
5       14     NULL 
6       18     NULL 
7       20     18
8       22     18
9       30     24

Use lag() :

select t.*, col2 - lag(col2, 6) over (order by col1) as diff6
from t;

The second (and not frequently used) argument to lag() and lead() is offset. It returns NULL if the value is not there, which seems to be exactly what you want.

Lag() is the straight option. Below is an another way using JOIN.

WITH STable
AS
(
    SELECT col1, col2, ROW_NUMBER () OVER (ORDER BY col1) AS rownum FROM table
)

Select x.col1, x.col2, x.col2 - y.col2 AS diff
from STable x
Left Join STable y
ON x.rownum = y.rownum + 6

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