BookmarkSubscribeRSS Feed
Guptashwe
Calcite | Level 5

In the below picture, TABLE A has brand and then first.brand loan row contains total.

 

What I am want to do is create a desired table where the (first.brand row value = first row current value – following rows value ) and if its not the first.brand then value as the current value as show in the table 2.

 

 

table.png 

 

Regards

BMW

2 REPLIES 2
DJongman
Obsidian | Level 7

Hi Guptashwe,

 

You could do the following:

 

 

data have;
	infile datalines;
	input id brand $ loan;
	return;
	datalines;
1 mini 70
2 mini 30
3 mini 20
4 mini 10
5 toyota 80
6 toyota 40
;
run;

proc sql;
	create table have2 as
		select id, brand, loan, sum(loan) as loan_calc
			from have 
				group by brand;
quit;

proc sort
	data= have2;
	by id;
run;

data want;
	set have2;
	by brand;

	if first.brand then
		loan_calc = loan-(loan_calc-loan);
	else loan_calc = loan;
run;

 

 

mkeintz
PROC Star

Given your data are grouped by brand, this is a classic double DOW task in the data step. Read a group once to calculate the needed value.  Re-read the group using that  value an outputting the data:

 

data have;
	infile datalines;
	input id brand $ loan;
	return;
	datalines;
1 mini 70
2 mini 30
3 mini 20
4 mini 10
5 toyota 80
6 toyota 40
;
run;

data want (drop=_:);
  do until (last.brand);
    set have;
    by brand;
    if _loan=. then _loan=loan;
    else _loan=_loan-loan;
  end;
  do until (last.brand);
    set have;
    by brand;
    if _loan^=. then loan=_loan;
    output;
    _loan=.;
  end;
run;
--------------------------
The hash OUTPUT method will overwrite a SAS data set, but not append. That can be costly. Consider voting for Add a HASH object method which would append a hash object to an existing SAS data set

Would enabling PROC SORT to simultaneously output multiple datasets be useful? Then vote for
Allow PROC SORT to output multiple datasets

--------------------------

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 946 views
  • 1 like
  • 3 in conversation