carltianji
一张表有3个字段:年月、货名、量
200801 a 8
200801 b 6
200801 c 9
200802 a 9
200802 b 8
200802 d 9
200803 a 4
现在需要新求一个字段:用当月的某个货的量-上个月的这个货的量,如果这个货存在,则相减,否则就为当月的量,如:
200801 a 8 .
200801 b 6 .
200801 c 9 .
200802 a 1
200802 b 8 2
200802 d 9 9
200803 a 4 -5
请教高手,这样的程序怎么写?????
losttemple
lag function
carltianji
要按货名分组,相同货名的才相减
yulingq
困为我问的问题没人理睬,所以深知其苦。
所以自己写了些东西,
尽管看上去有些麻烦,但可以达到目的,如果没有其他更好的方法,你暂用这个解决问题吧。
data c;
input time product $ x@@;
cards;
200801 a 8
200801 b 6
200801 c 9
200802 a 9
200802 b 8
200802 d 9
200803 a 4
run;
proc sort data=c;
by product;
run;
data e;
set c;
if product='a'
then do
quan=dif(x);
end;
if product='b'
then do
quan=dif(x);
end;
if product='c'
then do
quan=dif(x);
end;
if product='d'
then do
quan=dif(x);
end;
if quan=. then quan=x;
run;
yulingq
得出结果后,再proc sort data=e;
by time;
就得到你要的结果了。
liuzzz6
这样程序仍然存在问题,比如200801 c 9,2月没有这个货,如果3月又有了,那么按你的程序,将是3月-1月的货,而不是“否则就为当月的量”了。
liuzzz6
data a;
input time product $ x@@;
cards;
200801 a 8
200801 b 6
200801 c 9
200802 a 9
200802 b 8
200802 d 9
200803 a 4
200803 c 10
run;
proc sort data=a;
by product time;
run;
data c;
set a;
t=input(put(time,6.),6.);
ct=t-lag(t);
cp=lag(product);
cx=lag(x);
if ct=1 and product=lag(product) then quan=x-cx;
if product=cp and ct>1 then quan=x;
drop t ct cp cx;
run;
yulingq
楼上的言之有理,你的程序简单适用。受教了。
按你的思路,最后的程序似乎这样就可以解决问题了,
if ct=1 then quan=x-cx;
else quan=x;
drop t ct cp cx;
run;
liuzzz6
是的,其实x-cx,可以直接就是dif(x)了,还可以更精简。至于200801,如果是日期格式,就得先input(put(time,6.),6.); 否则差值不会是1
liuzzz6
[quote]引用第7楼yulingq于2008-04-09 09:26发表的“”:
楼上的言之有理,你的程序简单适用。受教了。
按你的思路,最后的程序似乎这样就可以解决问题了,
if ct=1 then quan=x-cx;
else quan=x;
drop t ct cp cx;
.......[/quote]
您误解了,
if ct=1 and product=lag(product) then quan=x-cx;
if product=cp and ct>1 then quan=x;
这两种情况会有值,
其他的情况下,quan都会是缺失值。
yulingq
哦,处理逻辑问题上出现了差异,非常感谢!