将 SQL 的 first_value 和分区依据转换为 SAS
Translate SQL's first_value and partition by into SAS
我在 SQL
中有此代码
SELECT acc_id,
time,
approved_amount,
balance,
coalesce(approved_amount,
first_value(balance) OVER (PARTITION BY acc_id
ORDER BY time)) orig_amount
FROM table;
是否有可能以某种方式将其转换为 SAS?它在 proc sql
步骤中不起作用。
我不使用也不了解 SAS,但是如果它不支持 window 函数,您可以用连接替换它。我假设您想要 coalesce 的第二个参数作为 acc_id 组中最旧记录的余额,因此:
select acc_id,
time,
approved_amount,
balance,
coalesce(approved_amount, acc_id_to_balance.balance_fallback)
from table t
join (
select t.acc_id, t.balance as balance_fallback
from (
select acc_id, min(time) as min_time
from table
group by acc_id
) acc_id_to_min_time
join table t on acc_id_to_min_time.acc_id = t.acc_id and acc_id_to_min_time.min_time = t.time
) acc_id_to_balance on t.acc_id = acc_id_to_balance.acc_id
刚想好,没试过。如果最小时间重复,可能会出现问题,这将需要另一个级别的分组。
这就是您在 SAS 中的做法,因为与 SQL 不同,当您使用数据步骤时,它会按照数据在源数据集中出现的顺序处理数据。
data want;
set table ;
by acc_id time;
if first.id then first_balance=balance;
retain first_balance;
orig_amount = coalesce(approved_amount,first_balance);
run;
我在 SQL
中有此代码SELECT acc_id,
time,
approved_amount,
balance,
coalesce(approved_amount,
first_value(balance) OVER (PARTITION BY acc_id
ORDER BY time)) orig_amount
FROM table;
是否有可能以某种方式将其转换为 SAS?它在 proc sql
步骤中不起作用。
我不使用也不了解 SAS,但是如果它不支持 window 函数,您可以用连接替换它。我假设您想要 coalesce 的第二个参数作为 acc_id 组中最旧记录的余额,因此:
select acc_id,
time,
approved_amount,
balance,
coalesce(approved_amount, acc_id_to_balance.balance_fallback)
from table t
join (
select t.acc_id, t.balance as balance_fallback
from (
select acc_id, min(time) as min_time
from table
group by acc_id
) acc_id_to_min_time
join table t on acc_id_to_min_time.acc_id = t.acc_id and acc_id_to_min_time.min_time = t.time
) acc_id_to_balance on t.acc_id = acc_id_to_balance.acc_id
刚想好,没试过。如果最小时间重复,可能会出现问题,这将需要另一个级别的分组。
这就是您在 SAS 中的做法,因为与 SQL 不同,当您使用数据步骤时,它会按照数据在源数据集中出现的顺序处理数据。
data want;
set table ;
by acc_id time;
if first.id then first_balance=balance;
retain first_balance;
orig_amount = coalesce(approved_amount,first_balance);
run;