日期:2014-05-18  浏览次数:20840 次

请教大家这种转置怎么写?
客户 字段A 字段B 字段C
A 10 20 30
B 40 50 60
B 70 80 90


客户 字段类型 值
A 字段A 10
A 字段B 20
A 字段C 30
B 字段A 40
B 字段B 50
B 字段C 60
B 字段A 70
B 字段B 80
B 字段C 90

谢谢指点。

------解决方案--------------------
SQL code
select 客户,'字段A' as 字段类型,字段A as 值 from tb
union all
select 客户,'字段B' as 字段类型,字段B as 值 from tb
union all
select 客户,'字段C' as 字段类型,字段C as 值 from tb

------解决方案--------------------
SQL code

declare @T table([客户] varchar(1),[字段A] int,[字段B] int,[字段C] int)
insert @T
select 'A',10,20,30 union all
select 'B',40,50,60 union all
select 'B',70,80,90

select [客户],'[字段A]' as 字段类型,[字段A] as 值 from @T 
union all
select [客户],'[字段B]' as 字段类型,[字段B]  from @T 
union all
select [客户],'[字段C]' as 字段类型,[字段C]  from @T 
order by 1,3

/*
客户   字段类型    值
---- ------- -----------
A    [字段A]   10
A    [字段B]   20
A    [字段C]   30
B    [字段A]   40
B    [字段B]   50
B    [字段C]   60
B    [字段A]   70
B    [字段B]   80
B    [字段C]   90
*/