1

我的表格和数据如下,

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 表,一些 chequeNo 是相同的,但 myID 不同。myID 与 chequeNo 的关系看起来像一对多。我想做 1 比 1(1 个 myID 有 1 个 chequeNo)。所以,我需要使用更新语句。

我的更新声明如何?

4

2 回答 2

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)
于 2012-04-08T08:37:55.763 回答
0
select myid, chequeno +
' (' +
cast(ROW_NUMBER() OVER (partition by chequeno order by chequeno) as varchar) +' )' as chequeno
from @t1
于 2012-04-08T08:49:46.863 回答