请教一句子的写法[给分]

bax_csu 2005-11-18 02:54:55
有张表 tab_1,内容如下:

ID Name level Tag
-----------------------------
1 a 3 t
2 a 7 t
3 a 9 t
4 a 4 t
5 b 14 t
6 b 13 t
7 c 13 t
8 c 13 t
9 c 15 t

现在需要修改 Tag的值,要求是按照 Name 分组后,按照Level 排序,每组level值大的两个Tag值不变;其余修改Tag值为f .
结果应该是这样:

ID Name level Tag
-----------------------------
1 a 3 f
2 a 7 t
3 a 9 t
4 a 4 f
5 b 14 t
6 b 13 t
7 c 13 f
8 c 13 f
9 c 15 t

请教都有那些写法?谢谢回答
...全文
92 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bax_csu 2005-11-18
  • 打赏
  • 举报
回复
感谢楼上回复,完成后就加分; 不过现在想再变复杂一点,在上述得到的结果的基础上,再update表得到如下结果:

ID Name level Tag Num
-------------------------------
1 a 3 f 4
2 a 7 t 2
3 a 9 t 1
4 a 4 f 3
5 b 14 t 2
6 b 13 t 1
7 c 13 f 2
8 c 13 f 3
9 c 15 t 1

说明: 添加了一个字段,这个字段的得来是按照 Name 分组后,按照level 排序,把序号写在Num字段。 都有那些写法,谢谢回答
wangkenping 2005-11-18
  • 打赏
  • 举报
回复

declare @t table (id int,name varchar(20),level int,tag varchar(20))
insert into @t select 1,'a',3,'t'
union all select 2,'a',7,'t'
union all select 3,'a',9,'t'
union all select 4,'a',4,'t'
union all select 5,'b',14,'t'
union all select 6,'b',13,'t'
union all select 7,'c',13,'t'
union all select 8,'c',13,'t'
union all select 9,'c',15,'t'


update t
set t.tag='f'
from @t t where t.id in (select top 2 y.id from @t y where y.name=t.name order by y.level DESC)

select * from @t


id name level tag
----------- -------------------- ----------- --------------------
1 a 3 t
2 a 7 f
3 a 9 f
4 a 4 t
5 b 14 f
6 b 13 f
7 c 13 t
8 c 13 f
9 c 15 f
jxdjxd1111 2005-11-18
  • 打赏
  • 举报
回复
up
子陌红尘 2005-11-18
  • 打赏
  • 举报
回复
update t
set
Tag = 'f'
from
tab_1 t
where
t.id not in(select top 2 id from tab_1 where Name=t.Name order by level desc)

34,590

社区成员

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

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