2012-04-08 179 views
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 */ 

我想用更新statment區分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與chequeNo的關係看起來像是一對多。我想讓1比1(1個myID有1個chequeNo)。所以,我需要使用update語句。

我的更新語句的外觀如何?

+0

http://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows – 2012-04-08 07:57:48

+0

@Riateche的可能重複:相關,但並不是真正的重複,我認爲。雖然有*已經被其他人,更類似的問題。 – 2012-04-08 08:17:07

回答

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) 
0
select myid, chequeno + 
' (' + 
cast(ROW_NUMBER() OVER (partition by chequeno order by chequeno) as varchar) +')' as chequeno 
from @t1 
+0

歡迎使用StackOverflow:如果您發佈代碼,XML或數據樣本,**請**在文本編輯器中突出顯示這些行,然後單擊編輯器工具欄上的「代碼樣本」按鈕(「{}」)語法突出它! – 2012-04-08 09:00:57