聚合可能不会出现在WHERE子句中,除非它在

时间:2017-06-26 17:53:50

标签: sql-server

select 
    * 
from sap_stockmaster 
where itemid=9893 
and salemrp=1034.00 
and salemrp in(
    select 
        salemrp 
    from sap_stockmaster 
    where SUM(stkqty)>0
) 
order by salemrp desc

我想要记录的数量之和大于零,但得到以下错误

  

聚合可能不会出现在WHERE子句中,除非它在a中   包含在HAVING子句或选择列表中的子查询以及列   被聚合是一个外部参考。

1 个答案:

答案 0 :(得分:3)

对聚合进行过滤时,您应使用having而不是where

select * 
from sap_stockmaster 
where itemid=9893 
and salemrp=1034.00 
and salemrp in (select salemrp 
    from sap_stockmaster 
    group by salemrp
    HAVING SUM(stkqty)>0) 
order by salemrp desc

此外,这可能是更高效的写作连接或使用EXISTS

-- example with Exists

SELECT * 
FROM sap_stockmaster ss1
WHERE itemid=9893 
AND salemrp=1034.00 
AND EXISTS (SELECT 1 
    FROM sap_stockmaster ss2
    WHERE ss1.salemrp = ss2.salemrp
    GROUP BY ss2.salemrp
    HAVING SUM(ss2.stkqty)>0)
ORDER BY salemrp DESC