首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Proc SQL左加入聚合函数,省略零。

Proc SQL左加入聚合函数,省略零。
EN

Stack Overflow用户
提问于 2022-08-17 21:44:25
回答 1查看 54关注 0票数 -1

我在SAS 9.4中有两个数据集。一个是type_list,它包含14种不同的帐户类型。另一个是account_list,它包含数千个帐户。

我试图得到所有类型的列表,并统计每种类型中有多少帐户符合某些条件。关键的是,如果有零个匹配的帐户,我想要一个输出为零的行。例如:

代码语言:javascript
复制
TYPE    ACCOUNTS
type-1  104
type-2  0
type-3  56
...     ...

下面是我使用的查询:

代码语言:javascript
复制
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;

我得到的实际输出对于没有任何匹配帐户的类型没有行。例如:

代码语言:javascript
复制
TYPE    ACCOUNTS
type-1  104
type-3  56
...     ...
EN

回答 1

Stack Overflow用户

发布于 2022-08-18 12:27:53

左加入类型与帐户的计算子查询。使用COALESCE处理帐户中从未发生过的某些类型的情况。

示例:

类型7从未出现在帐户中。

代码语言:javascript
复制
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
  ;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73395234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档