我试图得到一个特定的变量列表的模式。当模式不是唯一的时,我希望返回模式的平均值,这样用于获取模式的子查询(在较大的查询中)就不会返回两个值。但是,当模式是唯一的时,由于某种原因,一般查询会返回一个缺失的值。
我有以下样本数据:
data have;
input betprice;
datalines;
1.05
1.05
1.05
6
run;
PROC PRINT; RUN;
proc sql;
select avg(betprice)
from
(select betprice, count(*) as count_betprice from have group by betprice)
having count_betprice = max(count_betprice);
quit;如果我将更多的观察添加到betprice字段,使模式不是唯一的,我就会得到平均值。
data have;
input betprice;
datalines;
1.05
1.05
1.05
6
6
6
run;
PROC PRINT; RUN;如何更改此查询,以便始终返回两个最频繁值的模式或平均值。
谢谢你在这方面的帮助。
发布于 2013-08-22 12:57:56
这很难,在SAS工作了12年之后,我不记得我曾经使用过没有分组的方法,我想它会产生意想不到的结果。
因此,对于一个查询,我的解决方案不是很好,因为它进行了两次分组。
一个查询版本:
proc sql;
select avg(betprice)
from ( select
betprice
, count(*) as count_betprice
from work.have
group by betprice) /* first summary */
where count_betprice
= select max(count_betprice)
from
(select
betprice
, count(*) as count_betprice
from work.have
group by betprice) /* same summary here */;
quit;使用中间表(如果需要的话使用视图)进行一些简化,而不是使用相同的子查询:
proc sql;
create table work.freq_sum
as select
betprice
, count(*) as count_betprice
from work.have
group by betprice
;
select avg(betprice)
from work.freq_sum
where count_betprice
= select max(count_betprice) from work.freq_sum;
quit;请注意,您可以通过PROC方法计算像模式和中位数这样的统计数据:
proc means data=have n mean mode median;
var betprice;
run;发布于 2013-08-22 14:00:43
你在SAS,为什么不让SAS计算统计,因为这是它擅长的.
ods output modes=want;
proc univariate data=have modes;
var betprice;
run;
ods output close;
proc means data=want;
var mode;
output out=final(keep=betprice) mean=betprice;
run;这不会花很长时间,对另一个程序员来说,你所做的事情要清楚得多,而且很容易编写代码。如果你不采用这种方式,你可以一步一步地做。
发布于 2013-08-22 12:56:03
首先,注意在外部查询上没有group by语句,而使用having子句。这是不对的。
下面是一个可行的解决方案:
proc sql;
create view WORK.V_BETPRICE_FREQ as
select betprice, count(*) as count_betprice
from HAVE
group by betprice
;
select avg(betprice) as final_betprice
from WORK.V_BETPRICE_FREQ
where count_betprice = (select max(count_betprice) from WORK.V_BETPRICE_FREQ)
;
quit;我用了一个视图来防止代码重复。如果视图中的查询是一个非常繁重的CPU操作,那么您可能需要用一个物理表代替它。
编辑作为反馈:我相信您在查询中遇到了困难,因为在外部查询时您需要:
因此,在最终结果中,我将第一个保留在外部查询中,而在另一个子查询中执行第二个查询。
https://stackoverflow.com/questions/18379429
复制相似问题