2011-03-31 94 views
1

我有以下的表的示例數據SQL比較並在相同的表

Customer  Location  ID Attribute1  Attribute2 
    Cust1  Loc1  1  High   None 
    Cust1  Loc1  2  High   None 
    Cust1  Loc1  3  Low   None 

基於上面的例子中的數據,所述第一2個記錄是重複的,最後一個是不重複的確定既重複&非重複記錄。所以,我需要創建兩個表,一個用於非重複記錄,另一個用於重複。沒有。此處顯示的屬性列僅爲示例,通常約爲10列。

表一

Customer  Location  ID Attribute1  Attribute2 
    Cust1  Loc1  1  High   None 

表二

Customer  Location  ID Attribute1  Attribute2 
    Cust1  Loc1  3  Low   None 

可這在一個SQL查詢來執行?

感謝您的任何建議, Javid

+4

您不能在一個查詢中插入(或創建)2個不同的表,無論如何,你爲什麼要把它分成兩張表? Id號碼2發生了什麼?這僅僅是刪除重複的中間步驟? [如果是這樣看到這個答案](http://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows/3822833#3822833) – 2011-03-31 21:46:16

+0

謝謝馬丁。你指出我正在尋找的鏈接。 – user320587 2011-04-01 14:32:06

回答

0

你可以做到這一點很容易....

(我曾在Oracle數據庫運行此查詢下面我不知道關於雲燕SQL服務器,但在SQL語句看它是做正確的操作)點

insert all 
when (Customer , Location , ID , Attribute1 , Attribute2) in 
    (select Customer , Location , ID , Attribute1 , Attribute2 
     from base_table 
     group by Customer , Location , ID , Attribute1 , Attribute2 
     having count(*)>1) then 
    into Table_One (Customer , Location , ID , Attribute1 , Attribute2) 
     values (Customer , Location , ID , Attribute1 , Attribute2) 
else 
    into table_two (Customer , Location , ID , Attribute1 , Attribute2) 
     value (Customer , Location , ID , Attribute1 , Attribute2) 
select distinct Customer , Location , ID , Attribute1 , Attribute2 from base_table 

當你擁有所有列的值複製這個查詢是非常有用的...

個,但在你的問題你給什麼作爲示例數據不必重複行..

看到ID列中的值..

請告訴這裏,如果你想檢查特定的列組相同..

+0

儘管ID列具有不同的值,但我需要忽略並將前兩個記錄視爲重複項。我設法使用評論中指向的鏈接創建一個解決方案到我原來的帖子。 – user320587 2011-06-29 04:13:45

+0

我看到了這個鏈接..但認爲你可能仍然在尋找插入到不同的表格,而不是刪除重複的記錄...我已經在我的項目中使用這種工作來存儲重複值以及... 和另外一件事關於非重複行問題... 如果您只想檢查一組列只用於檢查,那麼你可以只採取該列組只有在和獨特的條款... :) – 2011-06-29 05:11:36