简体   繁体   English

SQL中每6行之间的差异

[英]Difference between every 6th row in SQL

How I can calculate difference between every 6th row in SQL Server 2016? 如何计算SQL Server 2016中每第6行之间的差异? 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() : 使用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. lag()lead()的第二个参数(并且不经常使用lead()是偏移量。 It returns NULL if the value is not there, which seems to be exactly what you want. 如果该值不存在,它将返回NULL ,这似乎正是您想要的。

Lag() is the straight option. Lag()是直接选项。 Below is an another way using JOIN. 下面是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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