视图显示库存余量

实现效果:


CREATE VIEW  [dbo].[v_Show_StockInOrderItem]

AS
WITH cte_detail AS
(
   --已入库数量
SELECT s.ProductID,s.ColorsID,s.SizesID,s.Title,s.ColorsName,s.SizesName,s.Quantity AS qty 
FROM TheBeerHouse.StockInItems s 
LEFT JOIN TheBeerHouse.StockIn si ON si.StockInID = s.StockInID

WHERE si.Status='Audited'     --已审核的标志,

              --TheBeerHouse.StockIn相当于是一个订单,谁什么时间入库   

              --TheBeerHouse.StockInItems 与订单表相关联,具体这个订单入库的哪个产品,数量,颜色,尺码等


UNION ALL

--已出库数量
SELECT o.ProductID AS oProductID,o.ColorsID AS oColorsID,o.SizesID AS oSizesID,o.Title AS otitle,
o.ColorsName AS oColorsName,o.SizesName AS oSizesName,-o.Quantity AS qty
FROM TheBeerHouse.OrderItems o
LEFT JOIN TheBeerHouse.Orders oo ON oo.OrderID = o.OrderID

WHERE oo.ShippingStatus = 'ApplyShipped'       --已出库的标志

              --TheBeerHouse.Orders 出库订单,谁什么时间出库   

              --TheBeerHouse.OrderItems 与订单表相关联,具体这个订单出库的哪个产品,数量,颜色,尺码等

)

--把上边的结果都结合起来

,cte_qty AS
(
SELECT ProductID,SUM(qty) AS qty,Title,SizesID,SizesName,ColorsID,ColorsName      --qty为入库量-出库量也就是库存余量
FROM cte_detail
WHERE ProductID=ProductID AND ColorsID=ColorsID AND SizesID=SizesID
GROUP BY ProductID,Title,SizesID,SizesName,ColorsID,ColorsName
)
SELECT   ROW_NUMBER()  OVER(ORDER BY T.ProductID) AS '数据标识' 
,产品标识 = T.ProductID
,ROW_NUMBER()  OVER(ORDER BY t.ProductID) AS '序号'
,产品编号 = T.ProductID
,产品名称 = T.Title
,颜色=T.ColorsName
,尺码=T.SizesName
,入库总量=(SELECT ISNULL(SUM(s.Quantity),0)
FROM TheBeerHouse.StockInItems s 
LEFT JOIN TheBeerHouse.StockIn si ON si.StockInID = s.StockInID
WHERE si.Status='Audited' AND s.ProductID=T.ProductID AND s.SizesID=T.SizesID AND s.ColorsID=T.ColorsID)
,销售总量=(SELECT ISNULL(SUM(o.Quantity),0)
FROM TheBeerHouse.OrderItems o
LEFT JOIN TheBeerHouse.Orders oo ON oo.OrderID = o.OrderID
WHERE oo.ShippingStatus = 'ApplyShipped' AND o.ProductID=T.ProductID AND o.SizesID=T.SizesID AND o.ColorsID=T.ColorsID)
,库存数量 = ISNULL(T.qty,0)
FROM 
cte_qty AS T

GO
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值