我的查询包含太多的select语句。因此我使用了条件聚合。该查询引用SQL Server 2008中 Instock 表中的数据,最终查询如下所示:
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
from
Instock
where
Vendor = 'abc'
问题是需要包含的最后一个查询。它从OutStock
表中获取数据,但我希望在上面的表中包含该查询,以便将结果作为单行返回。我能够使用嵌套查询来满足要求,但我希望使用条件聚合获得相同的结果,以保证数据库性能的平滑性。
需要包含的查询是:
select
COUNT(Product) as Despatched
from
OutStock
where
DispatchDate between '2013-8-1' and '2014-2-1'
and Vendor = 'abc'`
因此,我希望将两者结合起来作为单个查询执行,这将返回单行
答案 0 :(得分:1)
只需在第一个查询的列列表中添加第二个查询,因为它只返回一行。试试这个。
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'
更新:
如果您想要每个模型的结果计数,请将subquery
转换为correlated subquery
。应该像
(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')
对于model
表格中的每个Instock
,count
中的outstock
将被计算在内。
或者您也可以使用Left Join
。首先使用模型计算model
表Outstock
中每个join
的计数结果返回Instock
表
....
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