I would like to update a record in a table
with columns c and d, where d is the max(sum(data))
for a.
But I get an error saying you cannot have an aggregate
of an aggregate. So I devised the following involving
two extra steps. The ultimare goal is step 3,
to update table 2 (our new table created from table1) with the
max of the sum of d for a,b. There must be a more elegant solution. What is it? Thanks.
ds
/* Step 1 */
select t1.a,t1.b,t2.c,sum(t2.d) as sumd
into #temp
from table1 t1, table2 t2 -- t1 is the original table
-- t2 is the new table
where
t1.a=t2.a
and
t1.b=t2.b
group by t1.a,t1.b,t2.c
/* Step 2 */
select t1.a,t1.b,t1.c,max(t1.sumd) as maxsumd
into #temp2
from #temp t1, table2 t2
where
t1.a=t2.a
and
t1.b=t2.b
group by t1.a,t1.b,t2.c
drop table #temp1
/* Step 3 */
update t2
set
c = t1.c,
d = t1.maxsumd
from #temp2 t1,table2 t2
where
t1.a=t2.a
and
t1.b=t2.b
drop table #temp2
with columns c and d, where d is the max(sum(data))
for a.
But I get an error saying you cannot have an aggregate
of an aggregate. So I devised the following involving
two extra steps. The ultimare goal is step 3,
to update table 2 (our new table created from table1) with the
max of the sum of d for a,b. There must be a more elegant solution. What is it? Thanks.
ds
/* Step 1 */
select t1.a,t1.b,t2.c,sum(t2.d) as sumd
into #temp
from table1 t1, table2 t2 -- t1 is the original table
-- t2 is the new table
where
t1.a=t2.a
and
t1.b=t2.b
group by t1.a,t1.b,t2.c
/* Step 2 */
select t1.a,t1.b,t1.c,max(t1.sumd) as maxsumd
into #temp2
from #temp t1, table2 t2
where
t1.a=t2.a
and
t1.b=t2.b
group by t1.a,t1.b,t2.c
drop table #temp1
/* Step 3 */
update t2
set
c = t1.c,
d = t1.maxsumd
from #temp2 t1,table2 t2
where
t1.a=t2.a
and
t1.b=t2.b
drop table #temp2