另一个表中的多个计数查询

时间:2020-02-06 14:41:40

标签: sas

我对SAS有疑问。我们有一个由犯罪组成的表格crimes(每行一种犯罪,其中包含更多信息,例如刑法条款或日期)。

Date        Article
——————————————-
2019-01-01  146
2019-01-01  122
2019-01-01  123
2019-01-01  123
2019-01-02  160
...

每年,我们都会收到一份调查问卷,以填写在某些类别(例如欺诈,凶杀等)中犯下的罪行。不幸的是,该调查表中的类别与我们自己的类别(刑法条款)不同。因此,我们必须定义哪些文章属于哪个调查类别。这些信息存储在名为definitions的表中。

在下面的示例中,有两篇文章(110、111)可以概括为“盗窃”,而三篇文章可以概括为“攻击”:

Category  Article  Query 
———————————————————————-
Theft     110      select count(*) from crimes where article = 110
Theft     111      select count(*) from crimes where article = 111
Robbery   130      select count(*) from crimes where article = 113
Assault   140      select count(*) from crimes where article = 140
Assault   141      select count(*) from crimes where article = 141
Assault   146      select count(*) from crimes where article = 146     

在我们的数据库crimes中,我们还有一列“文章”。现在的目标是阅读有多少种犯罪。

因此,我希望有一个这样的表,该表提供每个类别(表definitions中定义的类别)的犯罪数量:

Category    Count
———————————————————
Theft       10,038
Robbery        503
Assault      1,200

现在的问题是:获得期望结果的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我认为,您可以使用以下proc sql inner join

proc sql;
   create table want as
   select d.category,count(*) as count
   from crimes c
   inner join definitions d
   on d.Article = c.Article
   group by 
   d.category;
quit;

如果article表中的categorydefinitions之间存在关联,并且{{1}中有一个定义为article的犯罪行中有一行,它将起作用}表。

答案 1 :(得分:1)

一种方法是将definitions表转换为可以读入proc format的自定义格式,然后使用该自定义格式对组进行求和。这可以使代码更容易在以后使用。要制作自定义和动态格式,您只需要以下变量:startendlabelcategoryfmtname

如果您忘记了每个变量代表什么,请检查此paper,或者简单地使用伪格式并使用cntlout=选项读取输出表。

data fmt;
    length fmtname $32.
           label   $25.
    ;

    set definitions end=eof;

    fmtname = 'articlecat'; /* Format name */
    type    = 'C';          /* Format type. C = Character */
    start   = article;      /* Start lookup value */
    end     = article;      /* End lookup value */
    label   = category;     /* Custom format name to apply to start/end */
    output;

    /* Optional: Give a label for unknown articles using the special HLO variable */
    if(eof) then do;
        HLO = 'O'; /* Special variable representing 'other' */
        call missing(start, end);
        label = 'Unknown';
        output;
    end;

    keep start end fmtname type label hlo;
run;

/* Save the format */
proc format cntlin=fmt;
run;

现在,您可以在程序中的其他任何地方使用格式,而不必对定义文件进行任何连接。

proc sql noprint;
    create table want as
        select put(category, $articlecat.) as Category
            , count(*) as Count
        from crimes
        group by calculated Category
    ;
quit;
相关问题