2016-04-26 81 views
0

我有稅率表與主鍵taxid 的結構如下SQL Server:如何使用另一個表中的ID將ID填充到表中?

taxid Type noteID 
1  A 
2  G 
3  G 
4  G 

我也有一個noteTable表看起來像這樣

NoteID SNoteText 
456 Hellow joe 
457 Non-Taxable 
458 Non-Taxable 
459 Non-Taxable 

現在我需要填充taxType = G與noteID那Snotetext =非應稅

所以最終的結果會是怎樣遵循

taxid Type noteID 
1  A  
2  G 457  
3  G 458  
4  G 459  
  • 訂單並不重要,457可以在taxID 2或3或4中。我的意思是noteID 457和TaxID 2之間沒有鏈接,它可以在任何地方。
  • 要知道的重要關鍵是Snotetext =「不可納稅」的總數將始終與taxType = G相同。所以在這個例子中,有3行TaxType = G,並且有3行sNoteText =「Non-Taxable」,這很重要。

我希望有道理。感謝您的幫助

+0

那麼,爲什麼不只是用457填充所有的noteID?這完全沒有意義。 –

+0

,因爲這恰好現在有相同的sNoteText。但有一天,例如他們只想更新taxID 2的註釋到「Taxable」而不更新taxID的其餘部分。那有意義嗎? – BobNoobGuy

+0

但是如果你只是隨機分配NoteID有什麼關係?換句話說,爲什麼是3 = 457而不是459?稍後如果您只更改其中一個,則會影響其他記錄,具體取決於您分配的內容 –

回答

1

如果您沒有表之間的鏈接,然後創建它。類似這樣的:

create table #taxTable(taxid int, [type] char(1),noteID int) 
insert #taxTable(taxid,[type]) 
values (1,'A'),(2,'G'),(3,'G'),(4,'G'), 
(5,'A'),(6,'G'),(7,'G'),(8,'G'),(9,'G') 

create table #noteTable(NoteID int,SNoteText varchar(50)) 
insert #noteTable 
values 
(456, 'Hellow joe'), 
(457 ,'Non-Taxable'), 
(458 ,'Non-Taxable'), 
(459 ,'Non-Taxable') 

declare @cnt int 
select @cnt=COUNT(noteid) from #noteTable where SNoteText='Non-Taxable' 
-- It is possible to add 3rd CTE for cnt 

;with n as (select row_number() over(order by noteID) rn, 
noteId 
from #noteTable where SNoteText='Non-Taxable'), 
t as (select row_number() over(order by taxid) rn, 
taxid,[type], noteid from #taxtable where [type]='G') 
update t 
set noteID = n.noteid 
from n inner join t on n.rn= (t.rn%@cnt)+1 

select * from #taxtable 
相關問題