Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

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

Status
Not open for further replies.

NSMan

Technical User
Aug 26, 2004
72
US
Grrr....Apparantly SQL doesn't like the idea of using aggregate's in an update statement. I'm using the following select statement to select a count of children records, and link them to parent records. Problem is, when I try to run an update off of this statement, SQL politly informs me that "An aggregate may not appear in the set list of an UPDATE statement...". My easiest solution is to simply select the data into a temptable, and link it from there. Is there another way to make this work?

Code:
select 
 count(child.id),
 parent.id
from 
 object parent,
 object child
where 
 parent.typ=2 and
 child.typ=4 and 
 parent.id=child.link1
group by
child.link1,
parent.id
 
What does your update statement look like?

-SQLBill

Posting advice: FAQ481-4875
 
Code:
update parent 
set
 parent.a1=count(child.id)
from 
 object parent,
 object child
where 
 parent.typ=2 and
 child.typ=4 and 
 parent.id=child.link1
group by
child.link1,
parent.id,
parent.a1
 

I guess Update is a typo and it should be 'select', the correct sql should be:

Code:
select 
 count(child.id),
 parent.id
from 
 object parent,
 object child
where 
 parent.typ=2 and
 child.typ=4 and 
 parent.id=child.link1
group by
parent.id
 
is parentID unique?

if it is then this should work, untested of course
Code:
update o set o.a1 =z.ChildCount
from
(select 
 count(child.id) as ChildCount,
 parent.id as parentID
from 
 object parent,
 object child
where 
 parent.typ=2 and
 child.typ=4 and 
 parent.id=child.link1
group by
child.link1,
parent.id) z join object o on z.parentID = o.parentID

Denis The SQL Menace
SQL blog:
Personal Blog:
 
Easily done with derived table.

But. why are you GROUPing by parent.id and parent.a1?

------
"There's a man... He's bald and wears a short-sleeved shirt, and somehow he's very important to me. I think his name is Homer."
(Jack O'Neill, Stargate)
[banghead]
 
Oh yeah...derived tables...thanks!

About the grouping on a1, it was just an empty field, and I figured that might be what was hanging up the update statement...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top