Cukup tambahkan kueri kedua di daftar kolom kueri pertama karena hanya akan mengembalikan satu baris. Coba ini.
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'
Pembaruan :
Jika Anda ingin jumlah hasil setiap model, maka konversikan subquery
ke correlated subquery
. seharusnya seperti
(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')
Di sini untuk setiap model
di Instock
tabel masing-masing count
dalam outstock
akan dihitung.
Atau bisa juga menggunakan Left Join
. Pertama hitung jumlah setiap model
dalam Outstock
tabel join
hasilnya kembali ke Instock
tabel menggunakan model
....
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