CREATE VIEW UnitSalesView AS
(
SELECT
A.UnitID,
A.Balance + COALESCE(SUM(B.SalesQuantity), 0) - COALESCE(SUM(C.ReceiptAmount), 0) AS CurrentBalance
FROM
Units A
LEFT JOIN
Sales B ON A.UnitID = B.UnitID AND B.SalesDate < @recentDate
LEFT JOIN
Receipts C ON A.UnitID = C.UnitID AND C.ReceiptDate < @recentDate
GROUP BY
A.UnitID, A.Balance
)
UNION ALL
(
SELECT
A.UnitID,
NULL AS Balance,
COALESCE(SUM(B.SalesQuantity), 0) AS TotalSalesQuantity,
COALESCE(SUM(C.ReceiptAmount), 0) AS TotalReceiptAmount
FROM
Units A
LEFT JOIN
Sales B ON A.UnitID = B.UnitID AND B.SalesDate BETWEEN @startSalesDate AND @endSalesDate
LEFT JOIN
Receipts C ON A.UnitID = C.UnitID AND C.ReceiptDate BETWEEN @startReceiptDate AND @endReceiptDate
GROUP BY
A.UnitID
);
|