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

数据表格式转换
有数据如下
编号   单价   数量   金额   月份
101       1.1       10     11       1
101       1.2       10     12       2
102       1.3       10     13       2
102       1.4       10     13       3
102       1.5       10     13       3
102       1.6       10     13       3

如何转换格式如下

编号   1单价   1月数量   1月金额   2月单价   2月数量   2月金额   3月单价   3月数量   3月金额
101     1.1         10             11               1.2         10                   12         1.4           10             14      
101         0           0               0                 1.3         10               13           1.5             10           15
101         0           0               0                 0             0                   0             1.6           10             16

------解决方案--------------------
create table test(编号 int,单价 money,数量 int,金额 int,月份 int)
insert into test select 101,1.1,10,11,1
insert into test select 101,1.2,10,12,2
insert into test select 102,1.3,10,13,2
insert into test select 102,1.4,10,13,3
insert into test select 102,1.5,10,13,3
insert into test select 102,1.6,10,13,3
go

declare @sql varchar(8000)
set @sql= ' '

select @sql=@sql+ ',[ '+rtrim(月份)+ '月单价]=max(case 月份 when '+rtrim(月份)+ ' then 单价 end) '
+ ',[ '+rtrim(月份)+ '月数量]=sum(case 月份 when '+rtrim(月份)+ ' then 数量 end) '
+ ',[ '+rtrim(月份)+ '月金额]=sum(case 月份 when '+rtrim(月份)+ ' then 金额 end) '
from test group by 月份

set @sql= 'select 编号 '+@sql+ ' from test group by 编号 '

exec(@sql)
go

/*
编号 1月单价 1月数量 1月金额 2月单价 2月数量 2月金额 3月单价 3月数量 3月金额
------ -------- -------- -------- -------- -------- -------- --------- -------- --------
101 1.1000 10 11 1.2000 10 12 NULL NULL NULL
102 NULL NULL NULL 1.3000 10 13 1.6000 30 39
*/

drop table test
go
------解决方案--------------------
select d.编号,a.单价 as 1月单价, a.数量 as 1月数量, a.金额 as 1月金额,b.单价 as 2月单价,
b.数量 as 2月数量, b.金额 as 2月金额,c.单价 as 3月单价, c.数量 as 3月数量, c.金额 as 3月金额
from (select distinct 编号 from table01) D
left outer join
(select 编号, 单价, 数量, 金额 from table01 where 月份=1 ) a
inner join