我在SAS 9.4中有两个数据集。一个是type_list,它包含14种不同的帐户类型。另一个是account_list,它包含数千个帐户。
我试图得到所有类型的列表,并统计每种类型中有多少帐户符合某些条件。关键的是,如果有零个匹配的帐户,我想要一个输出为零的行。例如:
TYPE ACCOUNTS
type-1 104
type-2 0
type-3 56
... ...下面是我使用的查询:
PROC SQL;
CREATE TABLE summary AS
SELECT
type_list.type,
COUNT(account_list.account_number) AS accounts
FROM type_list
LEFT JOIN account_list
ON type_list.type = account_list.type
WHERE account_list.curr_balance > 1000
GROUP BY type_list.type;
QUIT;我得到的实际输出对于没有任何匹配帐户的类型没有行。例如:
TYPE ACCOUNTS
type-1 104
type-3 56
... ...发布于 2022-08-18 12:27:53
左加入类型与帐户的计算子查询。使用COALESCE处理帐户中从未发生过的某些类型的情况。
示例:
类型7从未出现在帐户中。
data types;
do type = 1 to 14;
input count @@;
output;
end;
stop;
datalines;
104 0 56 123 4 0 7 8 9 0 11 12 13 14
;
data accounts;
call streaminit (20220818);
do id = 1 to 1e5;
do until (type ne 7);
type = rand('integer', 1, 14);
end;
balance = rand ('integer', 25, 25000);
output;
end;
run;
proc sql;
create table want as
select
types.type
, types.count as type_count
, coalesce(amc.accounts_count,0) as accounts_count
from
types
left join
(select type, count(*) as accounts_count
from accounts
where balance > 21000
group type
) as amc /* counts of accounts meeting criteria */
on
types.type = amc.type
;

https://stackoverflow.com/questions/73395234
复制相似问题