标签:
;with jgcb as(select *,cast(‘1900-01-01‘ as datetime) 加工日期 from T2 UNIONselect * from T3) select a.*, (select sum(成本单价*数量)/sum(数量) from jgcb b where a.品名=b.品名 and a.日期>=b.加工日期 ) 截至成本单价 from T1 adrop table #Temp_1
go
drop table #Temp_2
go
drop table #Temp_3
go
create table #Temp_1(
Name varchar(200),
OutQTY numeric(18,4),
Price numeric(18,4),
moneys numeric(18,4),
Dates datetime
)
create table #Temp_2
(
Name varchar(200),
Price numeric(18,4),
CostQTY numeric(18,4)
)
Create table #Temp_3
(
Name varchar(200),
ProcessPrice numeric(18,4),
ProcessQTY numeric(18,4),
ProcessDate datetime
)
insert into #Temp_1
select ‘香蕉‘,10,30,300,‘2015-06-01‘union all
select ‘香蕉‘,5,35,175,‘2015-06-13‘
insert into #Temp_2
select ‘香蕉‘,5,100
insert into #Temp_3
select ‘香蕉‘,6,80,‘2015-05-10‘ union all
select ‘香蕉‘,5,40,‘2015-05-20‘ union all
select ‘香蕉‘,8,100,‘2015-06-05‘
select
distinct
t1.Name as 品名,
t1.OutQTY as 出库数量,
t1.Price as 单价,
t1.moneys as 金额,
t1.Dates as 日期,
t2.CostQTY*t2.Price as 期初成本金额,
c.P as 加工金额,
((t2.CostQTY*t2.Price)+c.P)/d.SumProcessQTY as 截至成本单价,
d.SumProcessQTY,
cast(((t2.CostQTY*t2.Price)+c.P)/(d.SumProcessQTY) as numeric(18,4))as UnCost
from #Temp_1 t1
left join #Temp_2 t2 on t1.Name=t2.Name
left join (select distinct
cet.Dates,
cet.Name,
sum(t3.ProcessPrice* t3.ProcessQTY)as P
from #Temp_1 cet
left join #Temp_3 t3 on cet.Name=t3.Name and cet.Dates>=t3.ProcessDate
group by cet.Dates,cet.Name
)c on c.Name=t1.Name and c.Dates=t1.Dates
left join (select
t1.Name,t1.Dates,
sum(distinct t3.ProcessQTY) as SumProcessQTY
from #Temp_1 t1
left join #Temp_3 t3 on t1.Name=t3.Name and t1.Dates>=t3.ProcessDate
group by t1.Name,t1.Dates)d on d.Name=t1.Name
标签:
原文地址:http://www.cnblogs.com/lantianhf/p/4574721.html