销售表T1
品名 出库数量 单价 金额 日期
香蕉 10 30 300 2015-06-01
香蕉 5 35 175 2015-06-13
期初成本表T2
品名 成本单价 数量
香蕉 5 100
加工表T3
品名 单价 数量 加工日期
香蕉 6 80 2015-05-10
香蕉 5 40 2015-05-20
香蕉 8 100 2015-06-05
如何得到下面结果:此结果由T1加一截至成本单价字段得来,其截止成本单价计算方法为:(表T2品名金额)+(表T3小于等于T1日期金额)/(对应T2数量+T3小于等于T1日期数量) 后四舍五入单价,即T2表对应品名金额加T1表小于等于日期之前的T3表品名金额之和除以两表数量计算出的对应平均单价,可以参看下面列式
品名 出库数量 单价 金额 日期 截至成本单价
香蕉 10 30 300 2015-06-01 5.36 = (5*100)+(6*80)+(5*40) / (100+80+40)
香蕉 5 35 175 2015-06-13 6.19 = (5*100)+(6*80)+(5*40)+(8*100) / (100+80+40+100)
答案1
------------------------------------------------------------------------------------------
sql2005
;
with
jgcb
as
(
select
*,
cast
(
‘1900-01-01‘
as
datetime) 加工日期
from
T2
UNION
select
*
from
T3)
select
a.*,
(
select
sum
(成本单价*数量)/
sum
(数量)
from
jgcb b
where
a.品名=b.品名
and
a.日期>=b.加工日期
) 截至成本单价
from
T1 a
sql2000
SELECT a.*,
(SELECT SUM(成本单价 * 数量) / SUM(数量)
FROM (SELECT *, cast(‘1900-01-01‘ AS datetime) 加工日期
FROM T2
UNION
SELECT *
FROM T3) b
WHERE a.品名 = b.品名 AND a.日期 >= b.加工日期) AS 截至成本单价
FROM T1 a
答案2
-----------------------------------------------------------------------
drop 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