BookmarkSubscribeRSS Feed
alicezwang96
Fluorite | Level 6

I have a table like this:

Yearmonth       ID        Sales

202001            123      1000

202002            123      1500

202003            123        800

202004            123      2000

202005            123      1300

202001             456     2000

202002             456     2500

202003             456     2700

 

I want to create a new table that calculates the % change between every yearmonth, group by the ID of the salesperson. How can I do this?

3 REPLIES 3
Dilmer
Calcite | Level 5

This is a possible solution although it is not in sql but it works

data have;
input Yearmonth ID Sales;
dif= (((lag(Sales) + Sales)*100)/lag(Sales))-100;
format dif 8.2;
Cards;
202001 123 1000
202002 123 1500
202003 123 800
202004 123 2000
202005 123 1300
202001 456 2000
202002 456 2500
202003 456 2700
;
Run;

 

Greetings Dilmer.

ballardw
Super User

You may want to show what you would expect from that example data. There is more than one way to interpret " change between every yearmonth" and at least one of those would be nasty in SQL because order of processing is not SQL's strong point.

Patrick
Opal | Level 21

Like this?

data have;
  input Yearmonth ID Sales;
  Cards;
202001 123 1000
202002 123 1500
202003 123 800
202004 123 2000
202005 123 1300
202001 456 2000
202002 456 2500
202003 456 2700
;

data want;
  set have;
  by id;
  format dif percent10.2;
  _lag_sales=lag(sales);
  if not first.id then
    do;
      dif=sales/_lag_sales;
    end;
  drop _lag_sales;
run;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 434 views
  • 0 likes
  • 4 in conversation