在SQL

时间:2018-10-17 21:28:01

标签: sql tsql

在最初具有“ ID”和“ Scope”列的表中,我想添加另一列“ SkipOccurrence”,该列显示“ Scope”列中值“ Skip”的第N次出现

ID|Scope  |SkipOccurrence|minID|maxID
--|-------|--------------------------
1 |Include|              |     |
2 |Include|              |     |
3 |Skip   |1             |1    |2
4 |Include|              |     |
5 |Skip   |2             |4    |4
6 |Include|              |     |
7 |Include|              |     |
8 |Skip   |3             |6    |7
9 |Include|              |     |

最后,我正在寻找一种方法来计算“范围”列中具有“包含”的行的ID范围。

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER()窗口功能:

select
    id,
    scope,
    case when scope = 'Skip' then n end as skipoccurrence
from (
  select
      id,
      scope,
      row_number() over(partition by scope order by id) as n
    from my_table
) x
order by id

答案 1 :(得分:0)

假设您要在添加新列后更新表格。

UPDATE a
SET a.SkipOccurrence = a.NextNumber
FROM (SELECT SkipOccurrence, ROW_NUMBER() OVER (ORDER BY ID) AS NextNumber
      FROM myTable
      WHERE Scope = 'Skip') a