2013-02-15 98 views
2

需要一些幫助搞清楚如何分割了一些數據如何在TSQL拆分數據

數據目前看起來像這樣

╔═════════════════════════════════════════════╗ 
║ Name Data1 Data2 Data3 Field1 field2 Field3 ║ 
╠═════════════════════════════════════════════╣ 
║ a  1  2  3  x  y  z ║ 
╚═════════════════════════════════════════════╝ 

我需要,使其看起來像這樣

分割數據
+-----------------+ 
| name data field | 
+-----------------+ 
| a  1  x | 
| a  2  y | 
| a  3  z | 
+-----------------+ 

任何人都可以幫我這個

+2

@ethrbunny問一些兩個答案後? – dezso 2013-02-15 19:52:56

回答

3

有很多方法可以做到這一點(只是羅在bluefeet的回答OK),但可以使用UNION ALL一個簡單的方法:

SELECT [Name], Data1 AS Data, Field1 AS Field 
FROM YourTable 
UNION ALL 
SELECT [Name], Data2 AS Data, Field2 AS Field 
FROM YourTable 
UNION ALL 
SELECT [Name], Data3 AS Data, Field3 AS Field 
FROM YourTable 

而且here is a fiddle與此演示(bluefeet提供)。

+0

該查詢還將您的水平表轉換爲垂直表。如果你想讓它保持並查詢它,請將它視爲一個視圖。 – RandomUs1r 2013-02-15 19:36:39

7

取決於您的SQL Server版本。在SQL Server 2008開始,您可以使用unpivot的數據CROSS APPLY

SELECT t.name, 
    x.Data, 
    x.Field 
FROM YourTable t 
CROSS APPLY 
(
    VALUES 
     (t.Data1, t.Field1), 
     (t.Data2, t.Field2), 
     (t.Data3, t.Field3) 
) x (Data, Field); 

SQL Fiddle with Demo

這也可以使用UNPIVOT和SQL Server 2005+的PIVOT函數來完成:

select name, data, field 
from 
(
    select name, left(col, len(col) -1) col, value, 
    row_number() over(partition by left(col, len(col) -1) order by col) rn 
    from 
    (
    select name, 
     cast([Data1] as varchar(10)) Data1, 
     cast([Data2] as varchar(10)) Data2, 
     cast([Data3] as varchar(10)) Data3, 
     [Field1], [field2], [Field3] 
    from yourtable 
) src 
    unpivot 
    (
    value 
    for col in ([Data1], [Data2], [Data3], 
       [Field1], [field2], [Field3]) 
) unpiv 
) u 
pivot 
(
    max(value) 
    for col in (data,field) 
) piv 

SQL Fiddle with Demo

均可以得到結果:

| NAME | DATA | FIELD | 
----------------------- 
| a | 1 |  x | 
| a | 2 |  y | 
| a | 3 |  z | 
+0

在2005年可以通過'UNION ALL' [Amended Fiddle](http://www.sqlfiddle.com/#!3/52999a/4) – 2013-02-15 19:40:18

+0

@MartinSmith謝謝。 – Taryn 2013-02-15 19:41:17

+0

我如何將交叉應用的結果轉儲到表中? – Greg 2013-02-15 19:58:16