2017-10-20 119 views
0

好日子,加入3表到1 - 1表是aggr表

我有3個單獨的表。 2個表頭(每行1個信息)和1個事務表(多行)。

我想將彙總表加入到表頭中。以下是我需要加入的3張桌子。請有人協助語法。

ARTRNDETAIL: 
SELECT 
    SalesOrder 
    TrnYear, 
    TrnMonth, 
    InvoiceDate, 
    StockCode, 
    QtyInvoiced 
FROM ArTrnDetail 

SORMASTER: 
SELECT 
    SalesOrder, 
    OrderDate, 
    ReqShipDate 
FROM SorMaster 

SorDetail: 
SELECT SalesOrder, 
     sum(MOrderQty) as OrderQty, 
     sum(MShipQty) as ShipQty, 
     MStockCode 
FROM SorDetail 
WHERE MOrderQty > 0 
GROUP By SalesOrder,MStockCode 

我已經加入了前兩個,因爲我想從SorMaster日期字段使用下表添加到ArTrnDetail表:不過,我不知道如何將彙總表添加到休息之後。請參閱我下面的嘗試:

SELECT 
    ArTrnDetail.SalesOrder 
    TrnYear, 
    TrnMonth, 
    InvoiceDate, 
    StockCode, 
    QtyInvoiced, 
    SorMaster.OrderDate, 
    SorMaster.ReqShipDate 
FROM ArTrnDetail 

INNER JOIN 
    SorMaster ON ArTrnDetail.SalesOrder = SorMaster.SalesOrder 

我現在需要的是加入匯聚表所得到的頂級表,但加入對SalesOrder和StockCode。

請有人協助。提前致謝 !

回答

0

你可以把裏面的CTE查詢和連接的結果

;WITH CTE1 AS (
    SELECT 
     ArTrnDetail.SalesOrder 
     TrnYear, 
     TrnMonth, 
     InvoiceDate, 
     StockCode, 
     QtyInvoiced, 
     SorMaster.OrderDate, 
     SorMaster.ReqShipDate 
    FROM ArTrnDetail 
    INNER JOIN SorMaster 
     ON ArTrnDetail.SalesOrder = SorMaster.SalesOrder) 
,CTE2 AS (
    SELECT SalesOrder, 
     sum(MOrderQty) as OrderQty, 
     sum(MShipQty) as ShipQty, 
     MStockCode 
    FROM SorDetail 
    WHERE MOrderQty > 0 
    GROUP By SalesOrder,MStockCode 
) 
SELECT <columns> 
FROM CTE1 
INNER JOIN CTE2 
    ON <your join condition>