第一次查询:
select
Batch,Shiplist_Qty,COUNT(X.Batch) as ALLOCATED,(Shiplist_Qty - COUNT(X.Batch)) as Variance
from dbo.FG_FILLIN as X
where X.Status in('KITTED','ALLOCATED') group by X.Batch,X.Shiplist_Qty
输出:
Shiplist_Qty ALLOCATED Batch Variance
2 2 CIP2 0
8 6 CIP4 2
第二次查询:
Select BAtch,
COUNT(X.Batch) as KITTED from dbo.FG_FILLIN as X
where X.Status='KITTED' group by X.Batch
输出:
Batch KITTED
CIP2 1
现在我需要加入这两个查询并显示类似的结果。
Shiplist_Qty ALLOCATED Batch Variance Kitted
2 2 CIP2 0 1
8 6 CIP4 2 0
谢谢你!
答案 0 :(得分:2)
试试这个:
select Batch, Shiplist_Qty,COUNT(X.Batch) as ALLOCATED,
(Shiplist_Qty - COUNT(X.Batch)) as Variance, ISNULL(Kitted, 0) as Kitted
from dbo.FG_FILLIN as X
LEFT OUTER JOIN
(
Select Batch,
COUNT(Y.Batch) as KITTED from dbo.FG_FILLIN as Y
where Y.Status='KITTED' group by Y.Batch
) Batches
ON X.Batch = Batches.Batch
where X.Status in('KITTED','ALLOCATED')
group by X.Batch,X.Shiplist_Qty, ISNULL(Kitted, 0)
答案 1 :(得分:1)
您可以使用subquery:
select
Batch,
Shiplist_Qty,
COUNT(X.Batch) as ALLOCATED,
(Shiplist_Qty - COUNT(X.Batch)) as Variance,
(select Count(Batch) from dbo.FG_FILLIN where Status='KITTED' and Batch = X.Batch) as Kitted
from dbo.FG_FILLIN as X
where X.Status in('KITTED','ALLOCATED') group by X.Batch,X.Shiplist_Qty