我想实现以下查询。我在这里想要的是比较销售的发票金额,所以我需要的字段是这些:
OSLP.SalesPerson|OINV.CardName|OINV.DocDate|OINV.DocNum|OINV.DocTotal|ORDR.DocDate|ORDR.DocTotal|OINV.GrosProfit
到目前为止我所做的是,
Declare @mindate date = '10.01.16', @maxdate date = '10.31.16'
SELECT DISTINCT
T6.SlpName [Sales Person],
T5.CardName [Customer Name],
T5.DocDate [TRA Date],
T5.DocNum [TRA No],
T5.DocTotal [TRA Total],
(SELECT SUM(T8.DocTotal) FROM ORIN T8 INNER JOIN RIN1 T9 ON T8.DocEntry=T9.DocEntry WHERE T8.DocDate BETWEEN @mindate AND @maxdate) [Credit Amnt],
T1.DocDate [SO Date],
T1.DocTotal [SO Total],
T5.GrosProfit [Gross Profit]
FROM RDR1 T0
INNER JOIN ORDR T1 ON T0.DocEntry = T1.DocEntry
left outer JOIN DLN1 T2 on T2.BaseEntry = T0.DocEntry
left outer JOIN ODLN T3 on T2.DocEntry = T3.DocEntry
left Outer JOIN INV1 T4 on T4.BaseEntry = T3.DocEntry AND T4.BaseLine = T2.Linenum AND T4.BaseType = 15
OR (T4.Basetype=17 and T4.BaseEntry=T0.DocEntry AND T4.BaseLine=T0.LineNum)
left outer JOIN OINV T5 on T5.DocEntry = T4.DocEntry
left outer JOIN OSLP T6 on T6.SlpCode = T1.SlpCode
WHERE T5.DocDate BETWEEN @mindate AND @maxdate
Group by
T6.SlpName, T5.CardName, T1.CardCode,
T5.DocDate, T5.DocNum, T5.DocTotal,
T1.DocDate, T1.DocTotal, T5.GrosProfit
ORDER BY
T5.CardName, T5.DocDate
如您所见,我包含了 ORIN(Credit Memo) 表来扣除 OINV.DocTotal 与 ORIN.DocTotal 的总和。
因此,此查询可以正常工作,但是,我无法获得那些没有相关文档(如销售订单或交货)的发票。只是,它只是发票。