Hi!
I want to update a column with subtotals on another column based on grouping. Do I have to do an inner join in a subquery
data T;
input ID $ L M;
Datalines;
B 1 10
B 1 20
C 1 30
C 2 40
D 1 50
D 1 60
D 2 70
;
proc sql;
alter table T add M1 numeric;
update T
set M1 =
(select sum(M) from T group by ID, L )
;
quit;
?
This might do the trick
proc sql;
select id, l, m, sum(m) as m1
from t
group by id, l
order by id, l
;
quit;
This might do the trick
proc sql;
select id, l, m, sum(m) as m1
from t
group by id, l
order by id, l
;
quit;
That works but as this is a part of the code, is there a solution with Update?
Try this
proc sql;
/* Create Temporary aggregates table */
create table sums as
select id, l, sum(m) as m1
from t
group by id, l
order by id, l;
/* Alter the table */
alter table T add M1 num;
/* Update the t table */
update t
set m1 = (select s.m1 from sums s where t.id=s.id and t.l=s.l);
/* Drop the temporary aggregates table */
drop table sums;
quit;
Hope this helps,
Ahmed
I also thought of that solution but I wanted to ask whether there was a shorter version through creation of mirror table and inner join within the subquery.
I will go with that solution since it's not feasible otherwise. Thanks.
please try below code
data T;
input ID $ L M;
Datalines;
B 1 10
B 1 20
C 1 30
C 2 40
D 1 50
D 1 60
D 2 70
;
proc sql;
create table want as select ID, L, M, sum(M) as sumM from T group by ID, L ;
quit;
Hi @cmemtsa
You cannot update the T table by using an inner query that uses this table as it is already in use.
I would suggest that you create another table:
proc sql;
create table T2 as
select *, sum(M) as M1
from T
group by
ID, L;
quit;
Best,
Thank you but is there a way to use Update with subquery and though a mirror table?
If you really want UPDATE .
data T; input ID $ L M; Datalines; B 1 10 B 1 20 C 1 30 C 2 40 D 1 50 D 1 60 D 2 70 ; proc sql; create table _t as select * from t; alter table T add M1 numeric; update T set M1 = (select sum(M) from _T where id=t.id and l=t.l ) ; quit;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.
Early bird rate extended! Save $200 when you sign up by March 31.
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.