将当前行与SQL Server中的上一行进行比较

时间:2017-05-11 12:45:58

标签: sql sql-server sql-server-2012 row

我有一个名为team的表,如下所示:我刚在第3列添加了row_number

RaidNo  OutComeID   RN
2           15      1
4           15      2
6           14      3
8           16      4
10          16      5
12          14      6
14          16      7
16          15      8
18          15      9
20          16      10
22          12      11
24          16      12
26          16      13
28          16      14
30          15      15
32          14      16
34          13      17

OutcomeId为16时,从1开始,16连续出现,逐个添加。结果就像

RaidNo  OutComeID   RN  Result
2           15      1   0
4           15      2   0
6           14      3   0
8           16      4   1
10          16      5   2
12          14      6   0
14          16      7   1
16          15      8   0
18          15      9   0
20          16      10  1
22          12      11  0
24          16      12  1
26          16      13  2
28          16      14  3
30          15      15  0
32          14      16  0
34          13      17  0

帮助我获得结果。

1 个答案:

答案 0 :(得分:4)

您可以使用以下查询:

SELECT RaidNo, OutComeID, RN,
       CASE 
          WHEN OutComeID <> 16 THEN 0
          ELSE ROW_NUMBER() OVER (PARTITION BY OutComeID, grp ORDER BY RN) 
       END AS Result
FROM (
   SELECT RaidNo, OutComeID, RN,
          RN - ROW_NUMBER() OVER (PARTITION BY OutComeID ORDER BY RN) AS grp
   FROM mytable) AS t
ORDER BY RN

字段grp标识具有相同OutComeID值的连续记录的切片(也称为岛)。外部查询使用grp来枚举属于'16'切片的每个记录。属于其他切片的记录将分配值0

Demo here