首页 > 解决方案 > SQL查询根据不同列的先前值计算行数

问题描述

我在 SAS 工作,我有一张看起来像这样的表

ID | Time | Main | lag_1 | lag_2
----------------------------------------------------------------------------
A  |  01  |   0  |   0   |  1  
A  |  03  |   0  |   0   |  1  
A  |  04  |   0  |   0   |  0  
A  |  10  |   1  |   0   |  0  
A  |  11  |   1  |   0   |  0  
A  |  12  |   1  |   0   |  0  
B  |  02  |   1  |   1   |  1  
B  |  04  |   0  |   1   |  1  
B  |  07  |   0  |   0   |  1  
B  |  10  |   1  |   0   |  0  
B  |  11  |   1  |   0   |  0  
B  |  12  |   1  |   0   |  0  

除了有多个ID。该表按 ID 和时间排序。在计算 Main 列中的总数(称为tot)之后,我试图计算两件事:

  1. 仅当 lag_1 在Main 变为 1之前的某个时间等于 1 时, Main 列中的总计数,例如tot_1;和
  2. 与 1 相同。但在这种情况下,对于 lag_2,调用变量tot_2

预期计算表会给我

tot | tot_1 | tot_2
--------------------
 7  |   3   |   6

因为tot_1应该是 3(从 ID = A + 3 从 ID = B),tot_2应该是 6(从 ID = A + 3 从 ID = B)。

我是这些类型细分的完整初学者,因此非常感谢任何帮助。

编辑:我希望 tot_2 >= tot_1 因为 lag_2 建立在 Main 的事件之上,这些事件比 lag_1 回溯的时间更长。

标签: sqlsasconditional

解决方案


在数据步骤中更容易做到。这样,您可以检查新 id 的开始并重置标志,以确定 lag_x 变量是否为真。

data want ;
  set have end=eof;
  by id time ;
  tot + main ;
  if first.id then call missing(any_lag_1,any_lag_2);
  if any_lag_1 then tot_1 + main ;
  if any_lag_2 then tot_2 + main ;
  if eof then output;
  any_lag_1+lag_1;
  any_lag_2+lag_2;
  keep tot: ;
run;

推荐阅读