正在使用:SQL Server 2012
我正在尝试在发票(第一至第二至第三...)之间获取使用量,无论其高低。 由于结余余额变为负值,因此前3个交易结余余额设置为0。如果期末余额可用,则仅作为期初余额转移到下一个交易。
请提供所有有价值的建议和支持,以改善查询结果。
我试图获得如下所述的结果(excel格式仅用于说明目的)。
DECLARE
@startDate DATETIME,
@endDate DATETIME,
@OpenBalance int
SET @startDate = '09/01/2018'
SET @endDate = '12/30/2018'
; WITH cteDates AS
(
SELECT
@startDate 'new_date',
@startDate 'end_date',
1 as level
UNION ALL
SELECT
DATEADD(DD,1,new_date) 'new_date',
DATEADD(DD,1,new_date),
level+1
FROM cteDates
WHERE DATEADD(dd,1,new_date) < @endDate
)
, cteInvoice AS
(
SELECT ProductID
,InvoiceNo
,InvoiceDate
,InvoiceQty
,LEAD(InvoiceDate) OVER (PARTITION BY ProductID ORDER BY InvoiceDate) AS
NextDate
FROM ##tmpInvoice AS h
JOIN cteDates ON InvoiceDate BETWEEN cteDates.new_date and
cteDates.end_date
)
, cteUsage AS
(
SELECT ProductID, TransactionDate, Quantity
FROM ##tmpUsage
JOIN cteDates ON TransactionDate BETWEEN cteDates.new_date and
cteDates.end_date
)
SELECT cteInvoice.*
,o.UsageQty
,ROW_NUMBER() OVER (PARTITION BY
cteInvoice.ProductID,CteInvoice.InvoiceDate ORDER BY
cteInvoice.InvoiceNo) AS RowNumber
FROM cteInvoice
OUTER APPLY (SELECT SUM(Quantity) AS UsageQty
FROM cteUsage
WHERE (cteInvoice.ProductId = cteUsage.ProductID)
AND (TransactionDate >= cteInvoice.InvoiceDate
AND TransactionDate < cteInvoice.NextDate)
GROUP BY cteUsage.ProductID) AS o
OPTION (MAXRECURSION 0); GO