2016-07-24 47 views
1

我有這樣一個表:如何複製列中的行值?

Service_order  Part_code1 Part_code2  Part_code3  Part_code4  Part_code5 

    4182864919 GH82-11218A GH96-09406A  GH81-13594A GH02-11552A  GH02-11553A 
    4182868153 GH97-17670B    
    4182929636 GH97-17260C GH02-10203A   
    4182953067 GH97-17940C    
    4182954688 GH82-10555A GH97-17852A  GH81-13071A  
    4182955036 GH97-17940C    

但是我想表明它在一個新的表是這樣的:

Service_order  partCodes 
    4182864919  GH82-11218A 
    4182864919  GH96-09406A 
    4182864919  GH96-09406A 
    4182864919  GH02-11552A 
    4182864919  GH02-11553A 
    4182868153  GH97-17670B 
    4182929636  GH97-17260C 
    4182929636  GH02-10203A 
. 
. 
.and so on... 

我試圖加入和聯合,但它並沒有給我結果我想要的。 該怎麼辦?

+0

這可能是糟糕的數據庫模式。 請閱讀有關數據庫規範化的更多信息: https://en.wikipedia.org/wiki/Database_normalization –

+0

您使用的數據庫是?請適當標記。 –

回答

2

在SQL Server中,一個簡單的方法來逆轉置使用APPLY

select t.service_order, v.part_code 
from t cross apply 
    (values(Part_code1), (Part_code2), (Part_code3), (Part_code4), (Part_code5) 
    ) v(part_code) 
where v.part_code is not null; 

在MySQL或SQL Server,您可以使用union all

select t.service_order, part_code1 as part_code from t where part_code1 is not null union all 
select t.service_order, part_code2 as part_code from t where part_code2 is not null union all 
select t.service_order, part_code3 as part_code from t where part_code3 is not null union all 
select t.service_order, part_code4 as part_code from t where part_code4 is not null union all 
select t.service_order, part_code5 as part_code from t where part_code5 is not null; 
+0

如果我們從兩張表中選擇,我們不應該加入另一張表嗎? – erfan

+1

@erfan。 。 。你的問題只提到一張表格,非常明確。如果你有多個表格,那麼你應該問另一個問題。如果您不瞭解'交叉應用',那麼一個好的開始就是文檔:https://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx。 –

+0

如果您可以看到自己的代碼「select t.service_order,v.part_code」,則有一個T表,您可以選擇服務訂單和選擇零件代碼的V表。我在談論那兩個。 – erfan

1

如果服務訂單可以有幾種partCodes ,您應該有一個包含複合鍵的表格作爲規範化的一部分。 在這種情況下,service_order和partCodes將是每行的唯一鍵。

假設你有一個SQL數據庫,使用這種模式,你只需要一個SELECT * FROM [table_name]