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

数据库转置问题!
我有个定额数据库:
物料描述     加工设备     加工工序     加工定额
32222           X-1               粗磨               5
32222           Y-1               细磨               4
32222           Z-1               终磨               2
352226         Q-1               前磨               10
352226         T-2               粗磨               2
352226         T-3               钝化               1




想把它变成:
物料描述   设备   粗磨   设备   细磨   设备   终磨   设备   前磨   设备   钝化。。。。。
32222         X-1     5         Y-1     4         Z-1     2
352226       T-2     2                                                 Q-1       10     T-3       1



请问该如何写啊?

------解决方案--------------------
常有人提到,用动态生成SQL语句的方法处理数据时,处理语句超长,无法处理的问题
下面就讨论这个问题:

/*-- 数据测试环境 --*/
if exists (select * from dbo.sysobjects where id = object_id(N '[tb] ') and OBJECTPROPERTY(id, N 'IsUserTable ') = 1)
drop table [tb]
GO

create table tb(单位名称 varchar(10),日期 datetime,销售额 int)
insert into tb
select 'A单位 ', '2001-01-01 ',100
union all select 'B单位 ', '2001-01-02 ',101
union all select 'C单位 ', '2001-01-03 ',102
union all select 'D单位 ', '2001-01-04 ',103
union all select 'E单位 ', '2001-01-05 ',104
union all select 'F单位 ', '2001-01-06 ',105
union all select 'G单位 ', '2001-01-07 ',106
union all select 'H单位 ', '2001-01-08 ',107
union all select 'I单位 ', '2001-01-09 ',108
union all select 'J单位 ', '2001-01-11 ',109

/*-- 要求结果
日期 A单位 B单位 C单位 D单位 E单位 F单位 G单位 H单位 I单位 J单位
---------- ----- ----- ----- ----- ----- ----- ---- ---- ---- ------
2001-01-01 100 0 0 0 0 0 0 0 0 0
2001-01-02 0 101 0 0 0 0 0 0 0 0
2001-01-03 0 0 102 0 0 0 0 0 0 0
2001-01-04 0 0 0 103 0 0 0 0 0 0
2001-01-05 0 0 0 0 104 0 0 0 0 0
2001-01-06 0 0 0 0 0 105 0 0 0 0
2001-01-07 0 0 0 0 0 0 106 0 0 0
2001-01-08 0 0 0 0 0 0 0 107 0 0
2001-01-09 0 0 0 0 0 0 0 0 108 0
2001-01-11 0 0 0 0 0 0 0 0 0 109
--*/

/*-- 常规处理方法*/
declare @sql varchar(8000)
set @sql= 'select 日期=convert(varchar(10),日期,120) '
select @sql=@sql+ ',[ '+单位名称
+ ']=s