取決於您的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 |
@ethrbunny問一些兩個答案後? – dezso 2013-02-15 19:52:56