我的表和数据如下,
declare @t1 table (myID varchar(200), chequeNo varchar(20));
insert into @t1 values('2011-01-03809','1925');
insert into @t1 values('2011-01-03810','1989');
insert into @t1 values('2011-01-03791','BIMB 256247');
insert into @t1 values('2011-01-03789','BIMB 256247');
insert into @t1 values('2011-01-03792','BIMB 256247');
insert into @t1 values('2011-01-03793','BIMB 256247');
insert into @t1 values('2011-13-00430','mbb 385030');
insert into @t1 values('2011-13-00431','mbb 385030');
insert into @t1 values('2011-01-03645','bmmb 003095');
insert into @t1 values('2011-08-00608','CIMB 376443');
insert into @t1 values('2011-08-00609','CIMB 385371');
insert into @t1 values('2011-04-00652','CIMB 512393');
insert into @t1 values('2011-13-00399','EBB 000639');
/* myID is a unique */
我想区分chequeNo使用更新语句。
我的预期结果如下,
myID | chequeNo
-----------------------------------
2011-01-03645 bmmb 003095
2011-01-03789 BIMB 256247 (1)
2011-01-03791 BIMB 256247 (2)
2011-01-03792 BIMB 256247 (3)
2011-01-03793 BIMB 256247 (4)
2011-01-03809 1925
2011-01-03810 1989
2011-04-00652 CIMB 512393
2011-08-00608 CIMB 376443
2011-08-00609 CIMB 385371
2011-13-00399 EBB 000639
2011-13-00430 mbb 385030 (1)
2011-13-00431 mbb 385030 (2)
基于@ t1表,虽然不同的myID,但是一些chequeNo是相同的。 myID与chequeNo的关系看起来像1对多。我想做1对1(1个myID有1个chequeNo)。所以,我需要使用update语句。
我的更新语句如何?
答案 0 :(得分:2)
可以使用排名功能对行进行重新编号。
UPDATE subquery
SET chequeNo = chequeNo + ' (' + CAST(sequence AS varchar(20)) + ')'
FROM
(
SELECT *
, sequence = ROW_NUMBER() OVER (PARTITION BY chequeNo ORDER BY myID)
, reverseSequence = ROW_NUMBER() OVER (PARTITION BY chequeNo ORDER BY myID DESC)
FROM @t1
) subquery
WHERE NOT (sequence = 1 AND reverseSequence = 1)
答案 1 :(得分:0)
select myid, chequeno +
' (' +
cast(ROW_NUMBER() OVER (partition by chequeno order by chequeno) as varchar) +' )' as chequeno
from @t1