如果条件符合数字,则更新与上面的行相同的行

时间:2018-03-06 14:31:26

标签: sql sql-server-2008

我有这样的数据

id      type
1.      a
2.      b
3.      c
4.      c
5.      d
6.      c
7.      c

id   type.    group
1.      a.          1
2.      b.          2
3.      c.          2
4.      c.          2
5.      d.          3
6.      c.          3
7.      c.          3

如果是c类,则组值取自上一行的值。  我可以用循环条件和更新来实现这个目标,但这需要花费很多时间,因为循环更新很多行

如何使用sql server 2008的单一更新语句实现此目的

2 个答案:

答案 0 :(得分:1)

这应该有效

declare @t table (id int primary key, val char(1));
insert into @t values 
       (1, 'a')
     , (2, 'b')
     , (3, 'c')
     , (4, 'c')
     , (5, 'd')
     , (6, 'c')
     , (7, 'c');
select * 
     , sum(case when val = 'c' then 0 else 1 end) over (order by id) as grp
from @t t 
order by id;

id          val  grp
----------- ---- -----------
1           a    1
2           b    2
3           c    2
4           c    2
5           d    3
6           c    3
7           c    3

按照以下链接进行正在运行的演示。

Demo

答案 1 :(得分:0)

我发布这个作为@palarazzi给出的答案的替代方案,这可能已经足够了。这个答案对任何数量的字母都很有用。

WITH cte AS (
    SELECT t1.id AS id1, t1.type AS type1, t2.id AS id2, t2.type AS type2
    FROM yourTable t1
    INNER JOIN yourTable t2
        ON (t1.id = t2.id AND t1.type <> 'c') OR
            (t1.id > t2.id AND t1.type = 'c' AND t2.type <> 'c')
),
cte2 AS (
    SELECT id1, type2,
        ROW_NUMBER() OVER (PARTITION BY id1 ORDER BY id2 DESC) rn
    FROM cte
)

SELECT
    id1 AS id, type2 AS type,
    DENSE_RANK() OVER (ORDER BY type2) [group]
FROM cte2
WHERE rn = 1;

Demo