2013-08-30 63 views
2

我有這樣單排多列合併到一列使用SQL Server

OrderNo Item_Description1 Rate1 Quantity1 Item_Description2 Rate2 Quantity2 Item_Description3 Rate3 Quantity3 
-------- ------------------ ------ ---------- ------------------ ------ ---------- ------------------ ------ ---------- 
1001  Laptop    50000 8   Air Conditioner 20000 10   Television   25000 12 
1002  Washing Machine 35000 10   Camera    4000 20   Speaker   1500 15 

從這個表我需要創建一個臨時表或表是這樣的:

OrderNo Item_Description Rate Quantity 
-------- ------------------ ------ ---------- 
1001  Laptop    50000 8 
     Air Conditioner 20000 10 
     Television   25000 12 
1002  Washing Machine 35000 10 
     Camera    4000 20 
     Speaker   1500 15 

是否有辦法我可以在SQL Server中執行此操作嗎?

+1

我想你應該通過標準化數據庫開始。 –

+0

UNPIVOT三次並加入結果 –

+0

您應該記住SQL中的表沒有它們自己的隱式順序。如果您完全按照上面顯示的方式創建臨時表,則無法按順序保留該臨時表,因此您可能希望保留「Order_No」列已滿,或添加用於排序/分組的列。 – RBarryYoung

回答

2
SELECT * FROM 
(select ORDER_NO,ITEM_DESCRIPTION1,RATE1,QUANTITY1FROM TABLE 
UNION 
select ORDER_NO,ITEM_DESCRIPTION2,RATE2,QUANTITY2 FROM TABLE 
UNION 
select ORDER_NO,ITEM_DESCRIPTION3,RATE3,QUANTITY3 FROM TABLE)AS A ORDER BY ORDER_NO 
+0

只有一句話:使用UNION ALL來避免DISTINCT處理。 – dnoeth

0

希望能幫到你!

select t.* from 
( 
    select order_No, Item_Description1 as Item_Desription, Rate1 as Rate 
    from Table 
    union 
    select order_No, Item_Description2 as Item_Desription, Rate2 as Rate 
    from Table 
    union 
    select order_No, Item_Description3 as Item_Desription, Rate3 as Rate 
    from Table 
) as t 
Order by t.order_No asc 

這是我的測試

the Table

select t.* from 
    (select id, apple1 as apple, orange1 as orange 
    from Test 
    union all 
    select id, apple2 as apple, orange2 as orange 
    from Test 
    union all 
    select id, apple3 as apple, orange3 as orange 
    from Test) as t 
order by t.id asc 

the result

+0

我可以自己試一試 – very9527

7

您還可以使用CROSS APPLY來unpivot的數據:

select t.order_no, 
    c.item_description, 
    c.rate, 
    c.quantity 
from yourtable t 
cross apply 
(
    select item_description1, rate1, quantity1 union all 
    select item_description2, rate2, quantity2 union all 
    select item_description3, rate3, quantity3 
) c (item_description, rate, quantity) 
1

試試這個

SELECT t.* 
FROM Table1 
OUTER APPLY 
(
    VALUES 
     ([OrderNo],item_description1, rate1, quantity1), 
     (NULL, item_description2, rate2, quantity2), 
     (NULL, item_description3, rate3, quantity3) 
) t([OrdNo],item_description, rate, quantity) 

SQL FIDDLE DEMO

或者使用@bluefeet答案用NULL

SELECT c.[OrderNo], 
    c.item_description, 
    c.rate, 
    c.quantity 
FROM Table1 t 
CROSS APPLY 
(
    SELECT [OrderNo],item_description1, rate1, quantity1 UNION ALL 
    SELECT NULL, item_description2, rate2, quantity2 UNION ALL 
    SELECT NULL, item_description3, rate3, quantity3 
) c ([OrderNo],item_description, rate, quantity) 

SQL FIDDLE DEMO