Easy Left Join SQL语法

时间:2017-08-21 09:24:52

标签: sql left-join

SQL新手,希望完成LEFT JOIN。

我有两个单独的表格,代码如下:

SELECT 
    StockCode, SalesOrder, SUM(OrderQty) 
FROM 
    dbo.IopSalesPerf
WHERE 
    dbo.IopSalesPerf.CustRequestDate BETWEEN '2017-07-01' AND '2017-07-31' 
    AND EntrySystemTime = 1
    AND Warehouse = '01' 
    AND StockCode = '001013'
GROUP BY
    StockCode,SalesOrder
ORDER BY 
    StockCode ASC

SELECT 
    SalesOrder, SUM(NetSalesValue), SUM(QtyInvoiced)
FROM 
    ArTrnDetail
GROUP BY
    SalesOrder

我想使用SalesOrder作为连接列,将最后一个表左键连接到第一个表。任何人都可以协助语法吗?

1 个答案:

答案 0 :(得分:0)

最简单的方法是:

SELECT * FROM
(
    SELECT StockCode,SalesOrder,sum(OrderQty) 
    FROM dbo.IopSalesPerf
    WHERE dbo.IopSalesPerf.CustRequestDate between '2017-07-01' and '2017-07-31' 
    and EntrySystemTime = 1 and Warehouse = '01' and StockCode = '001013'
    GROUP BY StockCode,SalesOrder
    Order BY StockCode ASc
) AS A
LEFT JOIN
(
    SELECT SalesOrder,sum(NetSalesValue),sum(QtyInvoiced)
    FROM ArTrnDetail
    Group by SalesOrder
) AS B
ON A.SalesOrder = B.SalesOrder