SQL Server 2012根据空值的出现分配ID

时间:2014-04-07 19:59:22

标签: sql sql-server tsql sql-server-2012

我有下表:

ID  Stop
---------
1   NULL
2   100
3   NULL
4   50
5   100
6   210
7   300
8   NULL
9   NULL
10  20
11  70

我要做的是创建一个新列,根据NULL值的位置分配ID。基本上,Stop列是停止花费的时间量,NULL值是运动所花费的时间。我想连续停止(id列是按时间顺序排列),以便能够用某种标识符进行识别。这就是我想要的:

ID  Stop    StopID
------------------
1   NULL    NULL
2   100     1
3   NULL    NULL
4   50      2
5   100     2
6   210     2
7   300     2
8   NULL    NULL
9   NULL    NULL
10  20      3
11  70      3

我一直在修改这个问题,但我似乎无法做到正确:

select a.id, a.Stop,
       (case when a.Stop IS NOT NULL
             then sum(case when a.Stop IS NOT NULL then 1 end) over (partition by x order by id)
        end) as StopID
from (select a.*,
             sum(case when a.Stop IS NOT NULL then 0 else 1 end ) over (order by id) as x
      from data a
     ) a

它产生以下结果:

ID  Stop    StopID
-------------------
1   NULL    NULL
2   100     1
3   NULL    NULL
4   50      1
5   100     2
6   210     3
7   300     4
8   NULL    NULL
9   NULL    NULL
10  20      1
11  70      2

1 个答案:

答案 0 :(得分:1)

create table #t (ID int, Stop int)

insert #t values
(1,   NULL),
(2,   100),
(3,   NULL),
(4,   50),
(5,   100),
(6,   210),
(7,   300),
(8,   NULL),
(9,   NULL),
(10,  20),
(11,  70)

select id, stop,
case when stop is null then null else sum(case when stop is null then 1 else 0 end) over(order by id) end as stop_id
from #t