数据规范化:切换列和数据行

时间:2017-03-16 03:03:50

标签: sql sql-server-2012

我有一张这样的表:

Table 1
ID   Data
1    Name
2    Adam
3    SEX
4    Male
5    AGE
6    27
7    Name
8    Bob
9    SEX
10   Male
11   AGE
12   28

我想将其转换为以下格式

ID  NAME  SEX   AGE
1   Adam  Male   27
2   Bob   Male   28

如何在Sql Server中执行此操作? 感谢

2 个答案:

答案 0 :(得分:1)

你走了:

insert into table2
select t1.Data "name", t2.Data "sex", t3.Data "Age"
from table1 t1,
table1 t2,
table1 t3
where (t1.ID + 4) % 6 = 0
and (t2.ID + 2) % 6 = 0
and t3.ID % 6 = 0
and t1.ID + 2 = t2.ID
and t1.ID + 4 = t3.ID
  

Adam MALE 27

     

Bob MALE 28

     

Alice FEMALE 99

我添加了一条额外的记录,以便仔细检查它是否会超出数据的前两次迭代。顺便说一句,由于您的数据未规范化,您将无法使用PIVOT

答案 1 :(得分:-1)

create table #tt
(id int, data varchar(20))

insert #tt
(id , data)
values
(1,'Name'),
(2,'Adam'),
(3,'SEX'),
(4,'Male'),
(5,'AGE'),
(6,'27'),
(7,'Name'),
(8,'Bob'),
(9,'SEX'),
(10,'Male'),
(11,'AGE'),
(12,'28')


create table #endResult
(ID int identity(1,1), Name varchar(50),SEX VARCHAR(6), Age int)

insert #endResult
(Name, SEX, Age )
select 
        t2.data as Name
        ,t4.data as SEX
        ,t6.data as Age 
from 
        #tt t1 
join 
        #tt t2 
    on 
        t1.data = 'Name'
    and 
        t1.id+1 = t2.id
join 
        #tt t3 
    on 
        t1.id+2 = t3.id
    and
        t3.data = 'SEX' 
join 
        #tt t4 
    on 
        t1.id+3 = t4.id
join
        #tt t5 
    on
        t1.id+4 = t5.id
    and
        t5.data = 'AGE'
JOIN
        #tt t6
    on
        t1.id+5 = t6.id




 select * from #endResult