I've used recursive
CTEs[
^] (Common Table Expressions) in the following sql - see CodeProject Article
How to use recursive CTE calls in T-SQL[
^]
My thinking went as follows ... filter out what I need from the Activation table first (ignoring the LotQty for now) ...
With T1(ProductNo, DispatchDate, LotQty)
AS
(
SELECT D.ProductNo, D.DispatchDate, D.LotQty
from Despatch D
INNER JOIN Activation A ON D.ProductNo = A.ProductNo AND D.DispatchDate < A.ActivationDate
)
Then do the same with what I
might want from the Replaced Table
With T2(ProductNo, DispatchDate, LotQty)
AS
(
SELECT D.ProductNo, D.DispatchDate, D.LotQty
FROM Despatch D
INNER JOIN Replaced R ON D.ProductNo = R.ProductNo AND D.DispatchDate < R.RecordDate
)
I want to get everything from T1 and only the stuff from T2 that I don't already have and put it into T3. I added the [Source] column just to show where the data was really coming from
T3(Source, ProductNo, DispatchDate, LotQty)
AS
(
SELECT 'T1', T1.* FROM T1
UNION SELECT 'T2', * FROM T2 where T2.ProductNo NOT IN (SELECT T1.ProductNo from T1)
)
A quick query of the results shows that Products 3,4,5,6 are getting the data from T1, Product1 is getting it from T2 and Product2 has no other data.
Finally do the grouping/totals etc using
Despatch
as the base so the whole thing together becomes
With T1(ProductNo, DispatchDate, LotQty)
AS
(
SELECT D.ProductNo, D.DispatchDate, D.LotQty
from Despatch D
INNER JOIN Activation A ON D.ProductNo = A.ProductNo AND D.DispatchDate < A.ActivationDate
),
T2(ProductNo, DispatchDate, LotQty)
AS
(
SELECT D.ProductNo, D.DispatchDate, D.LotQty
FROM Despatch D
INNER JOIN Replaced R ON D.ProductNo = R.ProductNo AND D.DispatchDate < R.RecordDate
),
T3(Source, ProductNo, DispatchDate, LotQty)
AS
(
SELECT 'T1', T1.* FROM T1
UNION SELECT 'T2', * FROM T2 where T2.ProductNo NOT IN (SELECT T1.ProductNo from T1)
)
SELECT
D.LotQty,
ApprovedQty = count(D.ProductNo),
D.DispatchDate,
Installed = count(T3.ProductNo)
FROM Despatch D
LEFT OUTER JOIN T3 ON T3.ProductNo = D.ProductNo
WHERE D.LotQty = 20
GROUP BY D.LotQty, D.DispatchDate