读书人

求教一个sql语句多谢高手指教!--

发布时间: 2012-01-08 22:48:50 作者: rapoo

求教一个sql语句,谢谢高手指教!急急急----
我想实现一个功能,将数据库记录中,满足字段1的值不同,但字段2的值相同时的N条记录,且此N记录中的满足CreateTime(创建记录的时间)靠后的N-1条记录的字段2的值都改成一个随机数。不知道大家有没有明白?举个例子吧!
我现在有一个表Table1,结构和数据如下。
IDField1Field2CreateTime
10001a2007-01-01
20001e2007-01-01
30002a2007-01-11
40002b2007-01-11
50002c2007-01-11
60003a2007-01-12
70003b2007-01-12
80003c2007-01-12

现我想得出的结果是:将ID为3,6,7,8 的Field2的值都改成一个随机数字符串。
谢谢高手指教!



[解决办法]
update Table1 set Field2 = rand(id) where exists(select 1 from table1 a where a.Field2 = Table1.Field2 and a.ID <Table1.ID)
[解决办法]
declare @t table (
IDint,
Field1varchar(10),
Field2varchar(10),
CreateTime datetime
)

insert @t select
1, '0001 ', 'a ', '2007-01-01 '
union all select
2, '0001 ', 'e ', '2007-01-01 '
union all select
3, '0002 ', 'a ', '2007-01-11 '
union all select
4, '0002 ', 'b ', '2007-01-11 '
union all select
5, '0002 ', 'c ', '2007-01-11 '
union all select
6, '0003 ', 'a ', '2007-01-12 '
union all select
7, '0003 ', 'b ', '2007-01-12 '
union all select
8, '0003 ', 'c ', '2007-01-12 '

update t
set field2=char(ascii( 'A ')+cast(25*rand(id*10000) as int))
from @t t
where exists (
select 1 from @t
where field2=t.field2
and CreateTime <t.CreateTime
)


select * from @t

--结果
ID Field1 Field2 CreateTime
----------- ---------- ---------- ------------------------------------------------------
1 0001 a 2007-01-01 00:00:00.000
2 0001 e 2007-01-01 00:00:00.000
3 0002 G 2007-01-11 00:00:00.000
4 0002 b 2007-01-11 00:00:00.000
5 0002 c 2007-01-11 00:00:00.000
6 0003 U 2007-01-12 00:00:00.000
7 0003 A 2007-01-12 00:00:00.000
8 0003 F 2007-01-12 00:00:00.000

(所影响的行数为 8 行)

读书人网 >SQL Server

热点推荐