-2

I have a table with a bunch of columns like this:

ID, Name1, Name2, Name3, Title1, Title2, Title3, Email1, Email2, Email3

1, joe blow, Jane doe, john doe, president, secretary, janitor, no@no.com, yes@no.com,maybe@no.com

I am trying to split into multiple rows and insert into a new table with these column headers:

ID, Name, Title, Email

*1 - joe blow, president, no@no.com

1 - Jane doe, secretary, yes@no.com

1 - John Doe, janitor, maybe@no.com*

I cant find any info online that can help me out with this one. I have over 4K entries in this table alone so a manual entry is out of the question.

The ID has to be the same for each company. meaning all one row is one ID, the next row is another ID, etc.

4

2 回答 2

2

您没有指定您使用的 SQL Server 版本,但这个将多列转换为多行的过程称为 UNPIVOT。有几种方法可以 UNPIVOT SQL Server 中的数据。

如果您使用的是 SQL Server 2008+,那么您可以使用带有 VALUES 子句的 CROSS APPLY 来取消透视 3 组中的列:

select id, name, title, email
from yourtable
cross apply
(
  values
    (name1, title1, email1),
    (name2, title2, email2),
    (name3, title3, email3)
) c (name, title, email);

请参阅带有演示的 SQL Fiddle

如果您使用的是 SQL Server 2005+,则可以将 CROSS APPLY 与 UNION ALL 一起使用:

select id, name, title, email
from yourtable
cross apply
(
  select name1, title1, email1 union all
  select name2, title2, email2 union all
  select name3, title3, email3
) c (name, title, email);

请参阅带有演示的 SQL Fiddle

于 2013-09-27T11:28:26.513 回答
0

工会有问题吗?

select ID, Name1, Title1, Email1
from table
union all
select ID, Name2, Title2, Email2
from table
union all
select ID, Name3, Title3, Email3
from table

是否总是填充所有列?您可以使用 where 子句来确保填充了 name3(其中 name3 不为空),以确保填充新表中的所有值。

于 2013-09-27T00:09:23.197 回答