sum(CASE when KC_InsOuts.num >0 then KC_InsOuts.num else 0 end) as 本月入库,
sum(CASE when KC_InsOuts.num <0 then KC_InsOuts.num else 0 end) as 本月出库 ,
( S.KC_InitNum + sum(CASE when KC_InsOuts.num >0 then KC_InsOuts.num else 0 end) + sum(CASE when KC_InsOuts.num <0 then KC_InsOuts.num else 0 end)) as 当期库存
,(s.KC_price * sum(S.KC_InitNum) + sum(KC_InsOuts.num)) AS 总金额
,s.KC_UpperNumber AS 警戒高线库
,(( S.KC_InitNum + sum(CASE when KC_InsOuts.num >0 then KC_InsOuts.num else 0 end) + sum(CASE when KC_InsOuts.num <0 then KC_InsOuts.num else 0 end))-s.KC_UpperNumber) AS 超储数量
FROM dbo.KC_Spareparts S
JOIN (SELECT [KC_Bianhao]
,Kc_Ins.[KC_Code]
,Kc_Ins.[KC_Name]
,Kc_Ins.[KC_Specification]
,Kc_Ins.[KC_Unit]
,Kc_Ins.[KC_Number] AS num
FROM [AppBox].[dbo].[KC_SparepartsIns] Kc_Ins
UNION SELECT [KC_Bianhao]
,Kc_Outs.[KC_Code]
,Kc_Outs.[KC_Name]
,Kc_Outs.[KC_Specification]
,Kc_Outs.[KC_Unit]
,Kc_Outs.[KC_Number] * (-1) AS num
FROM [AppBox].[dbo].[KC_SparepartsOuts] Kc_Outs) KC_InsOuts
ON S.KC_Bianhao = KC_InsOuts.KC_Bianhao
group BY s.KC_Bianhao ,s.KC_Code,s.KC_Name,s.KC_Specification,s.KC_Unit,s.KC_price,s.KC_InitNum,s.KC_UpperNumber