首页 > 代码库 > SQL笔记---多表左联
SQL笔记---多表左联
这是实际场景当中的一个例子,拿出来分析总结思路。
-- SQL 查询 --
SELECT orderQuery.Rk_SkuCode ,
orderQuery.SkuName,
SUM(ISNULL(orderQuery.OrderTotal, 0))
- SUM(ISNULL(removeQuery.RemoveTotal, 0))
- SUM(ISNULL(pickQuery.PickTotal, 0))
- SUM(ISNULL(tempPickQuery.TempPickTotal, 0)) AS RealOrders ,
SUM(ISNULL(orderQuery.OrderTotal, 0)) AS Orders ,
SUM(ISNULL(removeQuery.RemoveTotal, 0)) AS Removes ,
SUM(ISNULL(pickQuery.PickTotal, 0)) AS Picks ,
SUM(ISNULL(stockQuery.StockTotal, 0)) AS Stocks ,
SUM(ISNULL(tempPickQuery.TempPickTotal, 0)) AS TempPicks
FROM ( SELECT Rk_SkuCode , do.Rk_SkuName AS SkuName,
SUM(do.UnitQty) AS OrderTotal
FROM dbo.SALE_Bill_Sale_Order o ,
dbo.SALE_Bill_Sale_Order_Detail do
WHERE o.Fk_ATS_Wfs_NodeId != 100100170
AND o.Fk_BillTypeId = 100100010
AND o.Pk_OrderId = do.Fk_OrderId
AND o.Fk_WarehouseId = 140416154556733
GROUP BY Rk_SkuCode,do.Rk_SkuName
) orderQuery
LEFT OUTER JOIN ( SELECT Rk_SkuCode ,
SUM(rd.Quantity) AS RemoveTotal
FROM dbo.WMS_Bill_Remove r ,
dbo.WMS_Bill_Remove_Detail rd
WHERE r.Pk_RemoveId = rd.Fk_RemoveId
AND r.Fk_WarehouseId = 140416154556733
AND r.Fk_BillTypeId = 100100110
AND r.Fk_ATS_Wfs_NodeId = 100300140
GROUP BY Rk_SkuCode
) removeQuery ON orderQuery.Rk_SkuCode = removeQuery.Rk_SkuCode
LEFT OUTER JOIN ( SELECT Rk_SkuCode ,
SUM(s.Quantity) AS PickTotal
FROM dbo.WMS_Stock s ,
dbo.WMS_Info_PartArea p
WHERE p.Pk_PartAreaId = s.Fk_PartAreaId
AND s.Fk_WarehouseId = 140416154556733
AND p.Ek_Type = 100100120
GROUP BY Rk_SkuCode
) pickQuery ON orderQuery.Rk_SkuCode = pickQuery.Rk_SkuCode
LEFT OUTER JOIN ( SELECT Rk_SkuCode ,
SUM(s.Quantity) AS StockTotal
FROM dbo.WMS_Stock s ,
dbo.WMS_Info_PartArea p
WHERE p.Pk_PartAreaId = s.Fk_PartAreaId
AND s.Fk_WarehouseId = 140416154556733
AND p.Ek_Type = 100100150
GROUP BY Rk_SkuCode
) stockQuery ON orderQuery.Rk_SkuCode = stockQuery.Rk_SkuCode
LEFT OUTER JOIN ( SELECT Rk_SkuCode ,
SUM(s.Quantity) AS TempPickTotal
FROM dbo.WMS_Stock s
WHERE s.Fk_WarehouseId = 140416154556733
AND s.Fk_LocationId = 140612114677165
GROUP BY Rk_SkuCode
) tempPickQuery ON orderQuery.Rk_SkuCode = tempPickQuery.Rk_SkuCode
GROUP BY orderQuery.Rk_SkuCode,orderQuery.SkuName
HAVING ( SUM(ISNULL(orderQuery.OrderTotal, 0))
- SUM(ISNULL(removeQuery.RemoveTotal, 0))
- SUM(ISNULL(pickQuery.PickTotal, 0))
- SUM(ISNULL(tempPickQuery.TempPickTotal, 0)) ) > 0