ALTER procedure [dbo].[XSJPB]
@ksrq datetime,
@jsrq datetime
as
create table #abc
(FENTRYID int,
FNAME nvarchar(255),
FEFFECTIVEDATE datetime,
FPRICE decimal(23,2))
insert into #abc
select t2.FENTRYID,t3.FNAME,t1.FEFFECTIVEDATE,t2.FPRICE
from T_SAL_PRICELIST t1,T_SAL_PRICELISTENTRY t2,T_BD_MATERIAL_L t3,T_BD_UNIT_L t4
where t1.FID=t2.FID
and t2.FMATERIALID=t3.FMATERIALID
and t2.FPRICEUNITID=t4.FUNITID
DECLARE @s NVARCHAR(4000)
SELECT @s = ISNULL(@s + ',', '') + QUOTENAME(rq)
FROM (select distinct convert(varchar(10),FEFFEctivedate,120) as rq from #ABC where FEFFEctivedate>=@ksrq and FEFFEctivedate<=@jsrq) as A ---列名不要重复
Declare @sql NVARCHAR(4000)
SET @sql='select r.*,s.平均单价 into abcd from
(select r.* from
(select FNAME,FEFFEctivedate,FPRICE from #abc where FEFFEctivedate>='''+CONVERT(VARCHAR(10),@ksrq,120)+ ''' and FEFFEctivedate<='''+CONVERT(VARCHAR(10),@jsrq,120)+ ''') as t
pivot
(max(t.FPRICE)
for t.FEFFEctivedate in ('+@s+')) as r) as r,
(select FNAME,cast(avg(FPRICE*1.0) as decimal(18,2)) 平均单价 from #abc where FEFFEctivedate>='''+CONVERT(VARCHAR(10),@ksrq,120)+ ''' and FEFFEctivedate<='''+CONVERT(VARCHAR(10),@jsrq,120)+ ''' group by FNAME) s
where r.FNAME=s.FNAME'
EXEC(@sql)
select * from abcd
推荐阅读