Msg 147 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list

StackOverflow https://stackoverflow.com/questions/23485210

Question

I am running SSMS 2008

select 
    A.JOBNUMBR as [Service Call], A.PONUMBER as [PO Number], 
    sum(A.QTYUNCMTBASE*A.UNITCOST) as [Committed Cost PO], 
    SUM(B.WS_Committed_Cost) as [Committed Cost WS], 
    (sum(A.QTYUNCMTBASE*A.UNITCOST)-SUM(B.WS_Committed_Cost)) as [Variance]
from 
    POP10110 A
LEFT JOIN 
    SV_Costs B on A.JOBNUMBR = B.Service_Call_ID and A.PONUMBER = B.Reference_TRX_Number and B.WS_Committed_Cost <> 0
where 
    A.Product_Indicator = 3
    and A.QTYUNCMTBASE <> 0
    and (sum(A.QTYUNCMTBASE * A.UNITCOST) - SUM(B.WS_Committed_Cost)) <> 0
group by 
    A.JOBNUMBR, A.PONUMBER
order by 
    A.JOBNUMBR, A.PONUMBER

I get the error MSG 147 in the subject line when I run this query. The 3rd where clause is the same as the aggregated column [Variance] which I am trying to filter down to <> 0. The query runs without this 3rd where clause.

I have been doing a bit of reading and understand that I need to include HAVING or a select statement in the where clause but I can't quite get the syntax right, any help would be appreciated.

Thank you

Tania

Was it helpful?

Solution

Sum is an aggregated column, invalid for use in your selection (WHERE clause). One solution is to wrap this on another SELECT. OR:

SELECT
          A.JOBNUMBR as [Service Call], 
          A.PONUMBER as [PO Number], 
          SUM(A.QTYUNCMTBASE*A.UNITCOST) as [Committed Cost PO], 
          SUM(B.WS_Committed_Cost) as [Committed Cost WS], 
          SUM(A.QTYUNCMTBASE*A.UNITCOST) - SUM(B.WS_Committed_Cost) as [Variance]
FROM      POP10110 A
LEFT JOIN SV_Costs B 
       ON A.JOBNUMBR = B.Service_Call_ID 
          AND A.PONUMBER = B.Reference_TRX_Number 
          AND B.WS_Committed_Cost <> 0
WHERE     A.Product_Indicator = 3
      AND A.QTYUNCMTBASE <> 0
GROUP BY  A.JOBNUMBR, A.PONUMBER 
   HAVING (SUM(A.QTYUNCMTBASE * A.UNITCOST) - SUM(B.WS_Committed_Cost)) <> 0
ORDER BY  A.JOBNUMBR, A.PONUMBER
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top