sql - 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)之后,我试图计算两件事:
- 仅当 lag_1 在Main 变为 1之前的某个时间等于 1 时, Main 列中的总计数,例如tot_1;和
- 与 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 回溯的时间更长。
解决方案
在数据步骤中更容易做到。这样,您可以检查新 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;
推荐阅读
- javascript - materializecss 在谷歌脚本网络应用程序的第二条记录后添加“,”(逗号)
- dynamics-crm - 什么是实体引用和查询表达式?请举几个简单的例子
- java - 有多个孩子时如何检测父视图的滑动?
- java - 检查需要移动多少元素才能对数组进行排序的最佳方法是什么?
- jquery - bootstrap-select 默认样式似乎不正确
- linux - 即使状态已分离,pthread 中的内存泄漏
- javascript - 如何访问 config.json 文件中的 .env 变量?
- c# - 如何在 ASP.NET Core 中将 HTTP 响应干净地传播给类型化 HTTP 客户端的使用者
- python - 无法使用 dataframe.loc 提取通过 dataframe.series 添加列创建的数据框
- c++ - 如何进一步减少执行时间?