1

我有下表:

Id  Type 
1   A
2   B
3   C
4   A

我想创建一个新表来计算每种类型的行数。为每种类型计数创建每个表很容易,但我想让它的外观和性能更好,所以可以在一个查询中做到这一点吗?我想出了一个像下面这样的查询,但它不起作用。该错误表示“WHEN 子句 2 的结果与前面的结果的数据类型不同”。帮助表示赞赏,并提前感谢。

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; 
4

5 回答 5

2

SAS 解决方案是不要将 PROC SQL 用于这样的事情。SQL 总是会有点慢或更难/更混乱的异常编码(没有 NotTypeA 这会更容易)。在 SAS 中,PROC TABULATE 和 PROC FORMAT 将在之后通过快速转置轻松地为您提供。更多的代码,但更灵活。

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;
于 2013-03-11T14:58:57.413 回答
1

试试下面的代码:

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

代码根据评论更新。

    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
于 2013-03-11T05:59:32.480 回答
1

试试这个:

select type,count(*) NoofRows from tbl group by type
于 2013-03-11T06:22:30.137 回答
0

您可以通过执行以下操作找到计数SELECT

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

请参阅 MySQL GROUP BY(聚合)函数。

于 2013-03-11T06:00:48.130 回答
0
`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;
于 2013-11-17T12:41:15.483 回答