Du skal blot tilføje den anden forespørgsel i kolonnelisten for den første forespørgsel, da den kun vil returnere én række. Prøv dette.
SELECT Sum(CASE
WHEN MONTH = '2013-8-1' THEN CurrentStock
ELSE 0
END) AS CurrentStock,
Isnull(Sum(CASE WHEN MONTH = '2014-2-1' THEN CPU ELSE 0 END), 0) -
Isnull(Sum(CASE WHEN MONTH = '2013-8-1' THEN CPU ELSE 0 END), 0) AS CPU,
Sum(CASE WHEN Month = '2013-8-1' THEN NonCPUWIP ELSE 0 END) AS NonCPU,
Isnull(Sum(CASE WHEN MONTH = '2014-2-1' THEN ScrapDiscarded ELSE 0 END), 0) -
Isnull(Sum(CASE WHEN MONTH = '2013-8-1' THEN ScrapDiscarded ELSE 0 END), 0)AS Scrap,
Sum(CASE WHEN Month = '2013-8-1' THEN WaitingForApproval ELSE 0 END) AS WFA,
(SELECT Count(STBSerialNUMBER)
FROM OutStock
WHERE DispatchDate BETWEEN '2013-8-1' AND '2014-2-1'
AND Vendor = 'abc' ) as Despatched
FROM Instock I
WHERE Vendor = 'abc'
Opdatering:
Hvis du vil have resultatoptællingen for hver model, skal du konvertere subquery
det til correlated subquery
. burde være noget lignende
(SELECT Count(STBSerialNUMBER)
FROM OutStock O
WHERE o.model = i.model -- here is the change
AND O.DispatchDate BETWEEN '2013-8-1' AND '2014-2-1'
AND o.Vendor = 'abc')
Her for hver model
i Instock
tabel det respektive count
i outstock
vil blive beregnet.
Eller du kan også bruge Left Join
. Beregn først antallet af hver model
i Outstock
tabel join
resultatet tilbage til Instock
tabel ved hjælp af modellen
....
From Instock I Left Join
(SELECT Count(STBSerialNUMBER) OutStock_count,Model
FROM OutStock O
WHERE O.DispatchDate BETWEEN '2013-8-1' AND '2014-2-1'
AND o.Vendor = 'abc'
Group by Model) O on o.model = i.model