SAS:在proc sql中使用group by不按时间顺序分离实例

时间:2016-04-28 22:56:25

标签: group-by sas proc-sql

考虑以下SAS代码:

public function lockingPermissions($state, $role)
{
    $lockingPermissions = [
        'technician'    => [
            'new' => [
                'lock'   => true, 
                'unlock' => false
            ],
            'checked' => [
                'lock'   => true, 
                'unlock' => false
            ]
        ],
                 .....
    ];

    return $lockingPermissions[$role][$state];
}

返回:

data test;
    format dt date9.
           ctry_cd $2.
           sn $2.;
    input ctry_cd sn dt;
    datalines;
    US 1 20000
    US 1 20001
    US 1 20002
    CA 1 20003
    CA 1 20004
    US 1 20005
    US 1 20006
    US 1 20007
    ES 2 20001
    ES 2 20002
    ;
run;

proc sql;
    create table check as
    select
        sn,
        ctry_cd,
        min(dt) as begin_dt format date9.,
        max(dt) as end_dt format date9.
    from test
    group by sn, ctry_cd;
quit;

我希望1 CA 07OCT2014 08OCT2014 1 US 04OCT2014 11OCT2014 2 ES 05OCT2014 06OCT2014 区分国家行动;也就是说,返回

proc sql

所以它仍然通过sn和ctry_nm对实例进行分组,但要注意日期,以便我有时间表。

2 个答案:

答案 0 :(得分:1)

您需要创建另一个分组变量:

data test;
  set test;
  prev_ctry_cd=lag(ctry_cd);
  if prev_ctry_cd ^= ctry_cd then group+1;
run;

proc sql;
    create table check as
    select 
        sn,
        ctry_cd,
        min(dt) as begin_dt format date9.,
        max(dt) as end_dt format date9.
    from test
    group by group,  sn, ctry_cd
    order by group;
quit;

答案 1 :(得分:0)

如果按照您的示例对数据进行排序,那么您可以在数据步骤中实现目标,而无需创建额外的变量。

data want;
keep sn ctry_cd begin_dt end_dt; /* keeps required variables and sets variable order */
set test;
by sn ctry_cd notsorted; /* notsorted option needed as ctry_cd is not in order */
retain begin_dt; /* retains value until needed */
if first.ctry_cd then begin_dt=dt; /* store first date for each new ctry_cd */
if last.ctry_cd then do;
    end_dt=dt; /* store last date for each new ctry_cd */
    output; /* output result */
end;
format begin_dt end_dt date9.;
run;