DATA Step, Macro, Functions and more

How can I get what I want in one step, proc sql;

Accepted Solution Solved
Reply
Contributor HG
Contributor
Posts: 23
Accepted Solution

How can I get what I want in one step, proc sql;

Thank you in advance!

My code:

data have;
input id word $6.;
cards;
1 Butter
1 Butter
1 Arm
2 Pole
2 Pole
2 Arm
2 Train
;
run;

proc sql;
  create table t1 as
    select id, count(id) as n1
   from have
     group by id;
  create table t2 as
    select id, count (id),word as n2 from
    have group by id,word;
  create table t3 as
    select id,count(id) as n3 from t2
    group by id;
  select t1.id,n1,n3 from t1,t3
    where t1.id=t3.id;
quit;

      id        n1        n3

       1         3         2

       2         4         3


Accepted Solutions
Solution
‎05-24-2012 04:39 PM
Respected Advisor
Posts: 4,644

Re: How can I get what I want in one step, proc sql;

Check table t2, I don't think it is what you expected... anyway, you seem to want for each ID, the total number of words and the number of distinct words. You can indeed get that in one SQL step :

proc sql;

select id, count(word) as totalWords, count(distinct word) as distinctWords

from have

group by id;

PG

PG

View solution in original post


All Replies
Solution
‎05-24-2012 04:39 PM
Respected Advisor
Posts: 4,644

Re: How can I get what I want in one step, proc sql;

Check table t2, I don't think it is what you expected... anyway, you seem to want for each ID, the total number of words and the number of distinct words. You can indeed get that in one SQL step :

proc sql;

select id, count(word) as totalWords, count(distinct word) as distinctWords

from have

group by id;

PG

PG
Contributor
Posts: 44

Re: How can I get what I want in one step, proc sql;

Nice! I've never seen the "count(distinct word)" syntax before!

Respected Advisor
Posts: 3,124

Re: How can I get what I want in one step, proc sql;

Of course the following one-step data step approach is not as robust as PG's SQL solution, as it requires same word cluster together within the same id:

data want; 

   do until (last.word);

     set have;

        by id word notsorted; 

        if first.id then call missing(n1,n2);

         n1+1;

    end;

    n2+1;

  if last.id then output;

run;

Haikuo

Valued Guide
Posts: 2,175

Re: How can I get what I want in one step, proc sql;

Haikuo

is almost at the optimal solution

Perhaps this might work for ordered data

Data want ;

N1=0;

  DO N2=1 by 1 UNTIL( last.ID );

    set have ;

     BY ID WORD;

     N1 + last.WORD ;

  END ;

run;

Of course it n

Message was edited by: Peter Crawford don't know why

Contributor HG
Contributor
Posts: 23

Re: How can I get what I want in one step, proc sql;

Thank you very much!!!Smiley Happy

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 258 views
  • 3 likes
  • 5 in conversation