如何将子查询的结果包含在WHERE子句中?
例如,我有以下声明(因为原文很大而减少):
SELECT o.ID AS OrderSpecsID, o.CustomerID, o.EstimateNo, o.OrderYear,
(SELECT COUNT(*)
FROM OrderSpecs AS os
WHERE (o.OrderID = OrderID)) AS AmendmentCount
FROM OrderSpecs AS o LEFT OUTER JOIN
Orders ON o.OrderID = Orders.ID
WHERE (o.CustomerID = 30)
我想在我的WHERE子句中包含AmendmentCount字段,如下所示:
WHERE (o.CustomerID = 30) AND (AmendmentCount > 0)
但是,如果我设置上述内容,则会出现以下错误:
无效的列名'AmendmentCount'
如何将AmendmentCount字段用于我的WHERE子句?
非常感谢,
罗布
答案 0 :(得分:3)
使用CTE或子查询:
with cte as (
SELECT o.ID AS OrderSpecsID, o.CustomerID, o.EstimateNo, o.OrderYear,
(SELECT COUNT(*)
FROM OrderSpecs AS os
WHERE (o.OrderID = OrderID)
) AS AmendmentCount
FROM OrderSpecs AS o LEFT OUTER JOIN
Orders
ON o.OrderID = Orders.ID
)
select *
from cte
where (CustomerID = 30) and (AmendmentCount > 0);
但是,如果你的情况,编写查询的更好方法可能是使用窗口函数:
select os.*
from (select os.ID AS OrderSpecsID, os.CustomerID, os.EstimateNo, os.OrderYear,
count(o.OrderId) over (partition by os.OrderId) as AmendmentCount
from OrderSpecs os left outer join
Orders o
on os.OrderID = o.ID
) os
where (CustomerID = 30) and (AmendmentCount > 0);
我有点不清楚CustomerId
上的过滤器在这种情况下是否应该在子查询或外部查询中。一个或另一个应该适合你正在做的事情。
答案 1 :(得分:0)
您可以在查询中添加带有联接的选择
FROM OrderSpecs
join (SELECT COUNT(*), OrderID
FROM OrderSpecs AS os
WHERE (o.OrderID = OrderID)) AS Amendment on Amendment.OrderID = OrderSpecs.OrderID