根据订单和列值查询相关行

时间:2016-10-24 06:18:09

标签: mysql sas

下表包含具有给定ID的操作何时开始和结束的日志,如operation列所示。

是否有办法生成包含以下列的SAS视图:runIDtypesessionNamestartTimeendtime和{ {1}}?它应该包含具有相同ID的相关行,durationInMinutesstartTime是彼此最接近的两行。

endTime

3 个答案:

答案 0 :(得分:3)

我认为你是这样想的。我自己加入并从那里开始。如果需要任何澄清,请告诉我。

data inData;
input id  operation $10.  time time. ;
format time hhmm. ;
datalines; 
1   starts  13:45
2   starts  13:46
3   starts  13:50
4   starts  13:55
2   ends    14:02
1   ends    14:50
3   ends    14:51
1   starts  15:25
3   starts  15:42
2   starts  15:51
4   ends    18:02
1   ends    18:09
3   ends    18:25
2   ends    18:30

;

proc sql;
create view tempView as
select a.id, a.operation as Type , a.Time as StartTime,
    b.operation as Type2,  b.time as EndTime,  
    INTCK('minute',a.Time,b.Time) as durationInMinutes
from indata a inner join indata b
    on a.id=b.id
group by a.id, b.Time
having durationInMinutes > 0 and a.operation='starts' and
    b.operation='ends'
order by a.id , StartTime, durationInMinutes
;
quit;

proc sql;
create view YourView as
select *
from TempView
group by ID , StartTime 
having min(durationInMinutes)=durationInMinutes
;
quit;

答案 1 :(得分:1)

您可以尝试这样的事情:

SET @time='00:00'; SET @cnt=0;

SELECT @cnt:=@cnt+1 runID, `id`, start_time, end_time, TIMEDIFF(end_time, start_time) duration 
FROM (
SELECT `id`, @time start_time, @time:=`time` end_time, `operation`
FROM yourTableName
ORDER BY `id`, `time`, `operation` DESC) tmp
WHERE tmp.`operation`='ends'

答案 2 :(得分:1)

在基础SAS中可能同样简单或容易。是否需要对其进行排序或索引 - 如果已编制索引,则可以跳过中间排序视图have_s

data have;
input id  operation $ time :time5.;
datalines;
1   starts  13:45
2   starts  13:46
3   starts  13:50
4   starts  13:55
2   ends    14:02
1   ends    14:50
3   ends    14:51
1   starts  15:25
3   starts  15:42
2   starts  15:51
4   ends    18:02
1   ends    18:09
3   ends    18:25
2   ends    18:30
;;;;
run;
proc sql;
  create view have_s as
    select id, operation,time
    from have
    order by id, time, operation descending;
quit;
data want/view=want;
  set have_s;
  by id;
  retain startTime;
  if first.id then startTime=.;
  if operation='starts' then startTime=time;
  else if operation='ends' then do;
    endTime=time;
    durationInMinutes = intck('minute',startTime,endTime,'c') ;
    output;
  end;
run;