Jeg tror, du kan bruge left joins til at gøre dette. Prøv denne forespørgsel, med dine eksempeldata producerer den det ønskede output, bortset fra ApprovedQty
, men jeg forstår ikke, hvordan du ankom til 12
for det med eksempeldataene:
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
dette ville udsende:
LOTQty ApprovedQty DispatchDate Installed
20 6 2013-08-07 5