I have three tables Despatch
, Activation
and Replaced
as below:
I think you could use left joins to do this. Try this query, with your sample data it produces the desired output, except for the ApprovedQty
, but I don't get how you arrived at 12
for that with the sample data:
select
d.LOTQty,
ApprovedQty = count(d.ProductNo),
d.DispatchDate,
Installed = count(a.ProductNo) + count(r.ProductNo)
from
Despatch d
left join
Activation a
on d.ProductNo = a.ProductNo
and d.DispatchDate < a.ActivationDate
and d.LOTQty = a.LOTQty
left join
Replaced r
on d.ProductNo = r.ProductNo
and d.DispatchDate < r.RecordDate
-- only count Replaced when there is no match in Activation
-- or DispatchDate is greater then ActivationDate
and (a.ActivationDate is null or a.ActivationDate < d.DispatchDate)
where
d.LOTQty = 20
group by
d.LOTQty, d.DispatchDate
this would output:
LOTQty ApprovedQty DispatchDate Installed
20 6 2013-08-07 5