表A
票号 报关费 报检费 押箱费
1 11 12 13
2 14 15 16
想变为表B
项目名 金额 票号
报关费 11 1
报检费 12 1
押箱费 13 1
报关费 11 2
报检费 12 2
押箱费 13 2
票号 报关费 报检费 押箱费
1 11 12 13
2 14 15 16
想变为表B
项目名 金额 票号
报关费 11 1
报检费 12 1
押箱费 13 1
报关费 11 2
报检费 12 2
押箱费 13 2
UNION ALL
SELECT 项目名 = '报检费', 金额 = 报检费, 票号 FROM 表A
UNION ALL
SELECT 项目名 = '押箱费', 金额 = 押箱费, 票号 FROM 表A
FROM 表A
UNPIVOT(
金额 FOR 项目名 IN([报关费], [报检费], [押箱费])
)UP
(票号 int,报关费 int,报检费 int,押箱费 int)
insert test
select 1, 11, 12, 13 union
select 2, 14, 15, 16declare @sql varchar(8000)
set @sql='select'
select @sql=@sql+' 项目名='''+name+''',金额='+name+',票号 from test union all select' from syscolumns
where id=object_id('test') and name<>'票号'
set @sql=left(@sql,len(@sql)-17)
print @sql
exec(@sql)
drop table test
insert A
select 1, 11, 12, 13
union all select 2, 14, 15, 16select 项目名='报关费', 票号, 金额=报关费 from A
union all
select 项目名='报检费', 票号, 金额=报检费 from A
union all
select 项目名='押箱费', 票号, 金额=押箱费 from A
order by 票号drop table A