SQL选择计数与case / when

时间:2013-03-11 05:55:55

标签: sql sas proc-sql

我有下表:

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; 

5 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:0)

您可以通过以下方式在SELECT中找到计数:

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

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

答案 4 :(得分: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;