/*
-- Author:Flystone
-- Date:2008-05-15
-- Version:V1.001
*/
-- Test Data: Ta
If object_id('Ta') is not null
Drop table Ta
Go
Create table Ta(拉号 varchar(2),产口编号 varchar(5),产品名称 varchar(6),日生产数量 int,日期 smalldatetime)
Go
Insert into Ta
select '01','k1084','A公仔',1000,'2008/05/10' union all
select '01','k1088','B公仔',500,'2008/05/11' union all
select '01','k1085','C公仔',5000,'2008/05/12' union all
select '01','k1085','D公仔',10000,'2008/05/13' union all
select '02','k1087','E公仔',6000,'2008/05/10' union all
select '02','k1088','B公仔',3000,'2008/05/11' union all
select '02','k1089','G公仔',9000,'2008/05/12' union all
select '02','k1084','A公仔',6000,'2008/05/13'
Go
--Start
declare @s varchar(8000)
select @s = isnull(@s+',','')+'['+convert(char(10),日期,120)+'] = max(case when datediff(d,日期,'''+ convert(char(10),日期,120)+''') = 0 then 日生产数量 else 0 end)'
from (select distinct 日期 from ta) a
exec('select 拉号,产口编号,产品名称,'+ @s + ' from ta group by 拉号,产口编号,产品名称
order by 拉号,产品名称')
--Result:
/*
拉号 产口编号 产品名称 2008-05-10 2008-05-11 2008-05-12 2008-05-13
---- ----- ------ ----------- ----------- ----------- -----------
01 k1084 A公仔 1000 0 0 0
01 k1085 C公仔 0 0 5000 0
01 k1085 D公仔 0 0 0 10000
01 k1088 B公仔 0 500 0 0
02 k1084 A公仔 0 0 0 6000
02 k1087 E公仔 6000 0 0 0
02 k1088 B公仔 0 3000 0 0
02 k1089 G公仔 0 0 9000 0
*/
--End