如何在SQL中拆分数据

时间:2013-02-15 19:32:20

标签: sql sql-server tsql unpivot

需要一些帮助来弄清楚如何分割一些数据

数据当前看起来像这样

╔═════════════════════════════════════════════╗
║ 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 个答案:

答案 0 :(得分:7)

取决于您的SQL Server版本。从SQL Server 2008开始,您可以使用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

这也可以使用SQL Server 2005 +中的UNPIVOTPIVOT函数来完成:

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 |

答案 1 :(得分:3)

有很多方法可以做到这一点(只需看看bluefeet的答案),但是一种简单的方法可以使用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提供)。