create table #tempbo
(
id nvarchar(255) ,
Fdate varchar(20),
FMonth varchar(20),
FName nvarchar(255),
fqty decimal(28,10),
Famount decimal(28,10)
)
INSERT INTO #tempbo
select '外购入库单' AS 数据类型,year(FDate)年,month(FDate)月,t.FName 物料名称 ,SUM(b.fqty) 总数量,isnull(SUM(b.Famount*1.17),0) 含税金额
from ICStockBill a join ICStockBillEntry b on a.finterid=b.finterid join t_ICItem t on t.FItemID=b.FItemID
where a.Fstatus in (1,2,3) and a.FROB=1 and a.FTranType=1 and a.fdate>='2018-01-01' and (t.FNumber like '%13.%' or t.FNumber like '%21.%')
GROUP BY FName,FDate
INSERT INTO #tempbo
select '外购退料单' AS 数据类型,year(FDate)年,month(FDate)月,t.FName 物料名称,SUM(0-b.fqty) 总数量,isnull(SUM(0-b.Famount*1.17),0) 含税总金额
from ICStockBill a join ICStockBillEntry b on a.finterid=b.finterid join t_ICItem t on t.FItemID=b.FItemID where
a.Fstatus in (1,2,3) and a.FROB=-1 and a.FTranType=1 and a.fdate>='2018-01-01' and (t.FNumber like '%13.%' or t.FNumber like '%21.%')
GROUP BY FName,FDate
select * into #temp0 from(
select fdate,Fmonth,FName
,sum(case when id='外购退料单' then fqty else 0 end) as 外购退料单数量
,sum(case when id='外购退料单' then Famount else 0 end) as 外购退料单金额
, sum(case when id='外购入库单' then fqty else 0 end) as 外购入库单数量
, sum(case when id='外购入库单' then Famount else 0 end) as 外购入库单金额
from #tempbo
GROUP BY id,Fdate,FMonth,FName )a
select * from #temp0
select * into #temp00 from(
select fdate,FMonth,FName
,CEILING(sum(外购退料单数量)) 外购退料单数量
,round(sum(外购退料单金额),2) 外购退料单金额
,CEILING(sum(外购入库单数量)) 外购入库单数量
,round(sum(外购入库单金额),2) 外购入库单金额
from #temp0 GROUP BY Fdate,FMonth,FName)a
select fdate 年,Fmonth 月,fname 物料名称,外购退料单数量,外购入库单数量,
case when 外购入库单金额=0 then 0 when 外购入库单数量=0 then 0 else 外购入库单金额/外购入库单数量 end
平均单价,外购退料单金额,外购入库单金额,
case when 外购入库单金额-外购退料单金额=0 then 0 else 外购入库单金额-外购退料单金额 end 外购材料净额
--,外购退料单金额/外购退料单金额 比率
,case when 外购退料单金额=0 then 0 when 外购入库单金额=0
then 0 else 外购退料单金额/外购入库单金额 end 退货比率,
from #temp00 group by fdate ,Fmonth ,fname,外购退料单数量,外购入库单数量,外购入库单金额,外购退料单金额
可以每月合计了,但是外购入库单金额/sum(外购入库单金额) 就是不对