Вопрос

I have the following table:

Id  Type 
1   A
2   B
3   C
4   A

I would like to create new table that counts the number of rows which each type has. It is easy to create each table for each type counting, but I would like to make it better in looks and also the performance, so is it possible to do this in one query? I have come up with a query like below but it does not work. The error said that "Result of WHEN clause 2 is not the same data type as the preceding result". Help is appreciated and thanks in advance.

PROC SQL;
   CREATE TABLE WORK.Statistics_Count AS
   SELECT 
      COUNT(Id) as total,
      COUNT(CASE WHEN Type = "A" then Id else . end) as typeA,
      COUNT(CASE WHEN Type = "B" then Id else . end) as typeB,
      COUNT(CASE WHEN Type = "C" then Id else . end) as typeC,
      COUNT(CASE WHEN Type <> "A" then Id else . end) as nonTypeA
   FROM WORK.ListTable;
QUIT; 
Это было полезно?

Решение

SAS solution is not to use PROC SQL for such a thing. SQL is always going to be a bit slower or harder/messier to code with exceptions (without the NotTypeA this would be easier). In SAS, PROC TABULATE and PROC FORMAT will give you that easily with a quick transpose afterwards. A bit more code but a lot more flexible.

data have;
input Id Type  $;
datalines;
1  A
2  B
3  C
4  A
;;;;
run;

proc format lib=work;
value $typeF (multilabel notsorted)
'A'='TypeA'
'B'='TypeB'
'C'='TypeC'
'B','C'='NonTypeA'
;;;;
run;

proc tabulate data=have out=want;
format type $typef.;
class type/mlf preloadfmt order=data;
tables type*n;
run;

proc transpose data=want out=want_t(drop=_NAME_);
var N;
id type;
run;

Другие советы

Try this:

select type,count(*) NoofRows from tbl group by type

Try below code :

Select Type , count(Type) as cnt
from WORK.Statistics_Count
group by Type

code updated as per comment.

    Select Type, count(Type) as cnt from  ( 
Select Type from WORK.Statistics_Count
where Type in ('A','B','C')

Union All

Select 'Others' as Type from WORK.Statistics_Count
where Type not in ('A','B','C'))z
group by Type

You can find the counts in a SELECT by doing:

SELECT COUNT(*)
FROM WORK.ListTable
GROUP BY Type

See MySQL GROUP BY (Aggregate) functions.

`proc sql noprint;`
 create table test as
 select * , 
   case 
    when type = "A" then count(id) 
   end as typeA
   ,
 case 
    when type = "B" then count(id) 
   end as typeB
   ,
 case 
    when type = "C" then count(id) 
   end as typeC
   ,
 case 
    when type ne "A" then count(id) 
   end as nontypeA

 from datain;
quit;


*  if you have many types, you can try this method below:  ;

data a;
 set datain;
   output;
  if type ne "A" then type="not A";
   output;
run;
  proc sql noprint;
  create talbe test1
   select * , count(id) as count
  from datain
  group by type
  order by id;
  quit;
proc transpose data=test1 out= final;
 id type;
 by id;
 var count;
run;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top