• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 51
  • Last Modified:

Update fields with SUM from a table - Help

Hello guys,

I tried to run this script but it complains:

 An aggregate may not appear in the set list of an UPDATE statement.

Could you give me a help on this?

Thanks a lot


update arfin set arfin.VALBAX=sum(bx.VALINI), arfin.VALJUR=sum(bx.VALJUR), arfin.VALDESC=sum(bx.VALDESC), 
                 arfin.VALOUTROS=sum(bx.VALOUTROS), arfin.VALMULTA=sum(bx.VALMULTA) from arfin_detalhe bx
       where arfin.codcad=bx.codcad and arfin.numdco= bx.numdco and arfin.codempresa = bx.codempresa
and bx.codcad = 7 and bx.numdco = '06042018-01'  and bx.codempresa ='E001'

Open in new window

0
hidrau
Asked:
hidrau
  • 2
2 Solutions
 
Kevin CrossChief Technology OfficerCommented:
Use a derived table as the source instead.

update a 
set a.VALBAX=bx.VALINI /* plus other SETs */
from arfin a
join (
   select  codcad, numdco, codempresa, valini = sum(VALINI) /* plus other sums */
   from arfin_detalhe 
   where codcad = 7 and numdco = '06042018-01'  and codempresa ='E001'
   group by codcad, numdco, codempresa
) bx on a.codcad=bx.codcad and a.numdco= bx.numdco and a.codempresa = bx.codempresa
;

Open in new window

1
 
Mark WillsTopic AdvisorCommented:
Or can use a CTE (Common Table Expression)
;with CTE_Update as
(  select codcad, numdco, codempressa
          , sum(VALINI) as VALINI
          , sum(VALJUR) as VALJUR
          , sum(VALDESC) as VALDESC
          , sum(VALOUTROS) as VALOUTROS
          , sum(VALMULTA) as VALMULTA
   from arfin_detalhe 
   where codcad = 7 
   and numdco = '06042018-01'  
   and codempresa ='E001'
   group by codcad, numdco, codempressa    
)  
   update a set VALBAX=C.VALINI
               ,VALJUR=C.VALJUR
               ,VALDESC=C.VALDESC 
               ,VALOUTROS=C.VALOUTROS
               ,VALMULTA=C.VALMULTA 
   from arfin a
   inner join CTE_Update C on C.codcad = a.codcad, C.numdco = a.numdco, C.codempresa = a.codempresa

Open in new window

But test first by doing a select * from arfin a inner join CTE_Update .....
2
 
hidrauAuthor Commented:
thanks a lot
0
 
hidrauAuthor Commented:
thanks a lot
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now