用一个值更新前10行,然后用另一个值更新10

时间:2014-03-24 18:08:39

标签: sql sql-server

我有一个表成员

members

id      data
1         a
2         a
3         a
4         b
5         b
6         b
7         b

在这里,我希望将第3个ID更新为a,接下来3个ID为b,接下来3个为a,依此类推。请帮我在sql中完成。

提前致谢。

3 个答案:

答案 0 :(得分:4)

请尝试以下声明:

update members set data = 'a' where ((id-1)/3)%2 = 0;
update members set data = 'b' where ((id-1)/3)%2 = 1;

答案 1 :(得分:1)

这应该有效(假设SQL Server 2005 +):

;WITH CTE1 AS
(
    SELECT  *,
            id2 = ROW_NUMBER() OVER(ORDER BY id) - 1
    FROM YourTable
), CTE2 AS
(
    SELECT  *, 
            id2/3%2 N
    FROM CTE1
)
UPDATE CTE2
SET data = CASE WHEN N = 0 THEN 'a' ELSE 'b' END;

SELECT *
FROM YourTable
带有演示的

Here is a sqlfiddle

答案 2 :(得分:0)

 select id into #temp from members order by id
 declare @i int = 'a'
 While Exists (select * from #temp)
 begin
 update members 
 set data = @i
 where id in (select top 1 id from #temp order by id)
 if(@i = 'a')
    set @i = 'b';
 else
   set @i ='a'
 delete from #temp where id in (select top 1 id from #temp order by id)
end

select * from members

上面的查询很棒,小而且精确,但是如果你想找到任何简单/非常简单的东西,这应该可行:)