为所有单位为 0 的初始观察设置标志 = 0 按组
Set flag=0 for all initial obsverations having units= 0 by group
我需要 SAS 或 PROC 方面的帮助 SQL。我有一个 table 如下所示:
prod_id
store_id
units
1
300
0
1
300
0
1
300
1
1
301
0
1
301
2
1
301
0
2
301
0
2
301
1
2
301
0
2
301
4
2
301
5
2
302
0
2
302
1
我要table应该是
prod_id
store_id
units
flag
1
300
0
0
1
300
0
0
1
300
1
1
1
301
0
0
1
301
2
1
1
301
0
1
2
301
0
0
2
301
1
1
2
301
0
1
2
301
4
1
2
301
5
1
2
302
0
0
2
302
1
1
如果对于任何 store_id 观察从零设置标志 =0 开始,直到对该商店和产品 ID 的第一次观察。
简而言之,只需为每个 store_id 和 prod_id 设置 flag=0 直到我们得到第一个非零的观察结果。
我试过了,但它只检测到第一个非零 obs 没有剩余。
data have;
input prod_ID store_id units;
cards;
1 300 0
1 300 0
1 300 1
1 301 0
1 301 2
1 301 0
2 301 0
2 301 1
2 301 0
2 301 4
2 301 5
2 302 0
2 302 1
;
run;
data want;
set have;
by store_id;
if first.store_id then n=0;
if units ne 0 then n+1;
flag=ifn(n=1 and units ne 0,1,0);
drop n;
run;
我觉得你只需要retain flag
,然后不用每次都计算,直接设置为1...
data want;
set have;
by prod_id store_id;
retain flag;
if first.store_id then flag=0;
if units gt 0 then flag=1;
drop n;
run;
我还将 prod_id
添加到 by 列表中,因为我认为这是正确的 - 你不希望 301 保留来自 prod_id 1.
的 flag=1
我需要 SAS 或 PROC 方面的帮助 SQL。我有一个 table 如下所示:
prod_id | store_id | units |
---|---|---|
1 | 300 | 0 |
1 | 300 | 0 |
1 | 300 | 1 |
1 | 301 | 0 |
1 | 301 | 2 |
1 | 301 | 0 |
2 | 301 | 0 |
2 | 301 | 1 |
2 | 301 | 0 |
2 | 301 | 4 |
2 | 301 | 5 |
2 | 302 | 0 |
2 | 302 | 1 |
我要table应该是
prod_id | store_id | units | flag |
---|---|---|---|
1 | 300 | 0 | 0 |
1 | 300 | 0 | 0 |
1 | 300 | 1 | 1 |
1 | 301 | 0 | 0 |
1 | 301 | 2 | 1 |
1 | 301 | 0 | 1 |
2 | 301 | 0 | 0 |
2 | 301 | 1 | 1 |
2 | 301 | 0 | 1 |
2 | 301 | 4 | 1 |
2 | 301 | 5 | 1 |
2 | 302 | 0 | 0 |
2 | 302 | 1 | 1 |
如果对于任何 store_id 观察从零设置标志 =0 开始,直到对该商店和产品 ID 的第一次观察。 简而言之,只需为每个 store_id 和 prod_id 设置 flag=0 直到我们得到第一个非零的观察结果。
我试过了,但它只检测到第一个非零 obs 没有剩余。
data have;
input prod_ID store_id units;
cards;
1 300 0
1 300 0
1 300 1
1 301 0
1 301 2
1 301 0
2 301 0
2 301 1
2 301 0
2 301 4
2 301 5
2 302 0
2 302 1
;
run;
data want;
set have;
by store_id;
if first.store_id then n=0;
if units ne 0 then n+1;
flag=ifn(n=1 and units ne 0,1,0);
drop n;
run;
我觉得你只需要retain flag
,然后不用每次都计算,直接设置为1...
data want;
set have;
by prod_id store_id;
retain flag;
if first.store_id then flag=0;
if units gt 0 then flag=1;
drop n;
run;
我还将 prod_id
添加到 by 列表中,因为我认为这是正确的 - 你不希望 301 保留来自 prod_id 1.