请教一条更新语句

jimsmo 2007-01-15 10:57:34
请教一条更新语句


表a
id num
100 10
101 10
102 10
103 20
104 20
105 30
106 30
107 30
108 40
如何写更新语句得到下面的结果
100 100
101 100
102 100
103 103
104 103
105 105
106 105
107 105
108 108

谢谢各位
...全文
162 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
akuzou 2007-01-15
  • 打赏
  • 举报
回复
declare @t table(id int,num int)
insert @t select 100,10
union all select 101,10
union all select 102,10
union all select 103,20
union all select 104,20
union all select 105,30
union all select 106,30
union all select 107,30
union all select 108,40

declare @i int,@a int
set @a=0
set @i=0
update @t set @a=case when num<>@i then id else @a end ,@i=case when num<>@i then num else @i end,num=case when num=@i then @a else id end,@i=num

select * from @t

--上面的方法主要借鉴一位朋友的语句,
方法不一定可取,但也是一种思路
marco08 2007-01-15
  • 打赏
  • 举报
回复
請樓主不要發重複的貼子, 看到我頭暈
jimsmo 2007-01-15
  • 打赏
  • 举报
回复
谢谢:marco08(天道酬勤)
marco08 2007-01-15
  • 打赏
  • 举报
回复
create table T(id int, num int)
insert T select 100, 10
union all select 101, 10
union all select 102, 10
union all select 103, 20
union all select 104, 20
union all select 105, 30
union all select 106, 30
union all select 107, 30
union all select 108, 40

update T set num=B.id
from(
select id=min(id), num from T group by num) B
where T.num=B.num

select * from T
--result
id num
----------- -----------
100 100
101 100
102 100
103 103
104 103
105 105
106 105
107 105
108 108

(9 row(s) affected)
jimsmo 2007-01-15
  • 打赏
  • 举报
回复
以上回复你给leo_lesley(leo)
jimsmo 2007-01-15
  • 打赏
  • 举报
回复
谢谢这位兄台的指教
但您这条语句的得到的结果是
100 100
101 100
102 100
103 100
104 100
105 100
106 100
107 100
108 100
这并不是我要得到的结果
marco08 2007-01-15
  • 打赏
  • 举报
回复
create table T(id int, num int)
insert T select 100, 10
union all select 101, 10
union all select 102, 10
union all select 103, 20
union all select 104, 20
union all select 105, 30
union all select 106, 30
union all select 107, 30
union all select 108, 40

update T set num=B.id
from(
select id=min(id), num from T group by num) B
where T.num=B.num

select * from T
leo_lesley 2007-01-15
  • 打赏
  • 举报
回复
update tablename set num = (select min(a.id) from tablename a where a.num = num)

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧