首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

数据表格式转换,该怎么处理

2012-02-01 
数据表格式转换有数据如下编号单价数量金额月份1011.1101111011.2101221021.3101321021.4101331021.510133

数据表格式转换
有数据如下
编号   单价   数量   金额   月份
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
(select 编号, 单价, 数量, 金额 from table01 where 月份=2 ) b


inner join
(select 编号, 单价, 数量, 金额 from table01 where 月份=3 ) c
on d.编号=a.编号 and d.编号=b.编号 and d.编号=c.编号
[解决办法]
create table test(编号 int,单价 decimal(5,1),数量 int,金额 int,月份 int)
insert test select 101,1.1,10,11,1
union all select 101,1.2,10,12,2
union all select 102,1.3,10,13,2
union all select 102,1.4,10,13,3
union all select 102,1.5,10,13,3
union all select 102,1.6,10,13,3

declare @s varchar(8000)
set @s= 'select 编号 '
select @s=@s+ ',sum(case 月份 when ' ' '+rtrim(月份)+ ' ' ' then 单价 else 0 end) as [ '+rtrim(月份)+ '月单价]
,sum(case 月份 when ' ' '+rtrim(月份)+ ' ' ' then 数量 else 0 end) as [ '+rtrim(月份)+ '月数量]
,sum(case 月份 when ' ' '+rtrim(月份)+ ' ' ' then 单价*数量 else 0 end) as [ '+rtrim(月份)+ '月金额] '
from test
group by 月份

select @s=@s+ ' from test
group by 编号 '

exec(@s)

drop table test
[解决办法]
樓主給出的數據和結果有很大出入。

热点排行