如何在SAS中为每次迭代执行多个case语句?

时间:2016-10-25 22:41:12

标签: sql sas runtime

我使用proc sql,并使用多个case语句在满足条件时添加0或1的列。它现在是一个很大的瓶颈,因为它必须在声明时扫描每个案例的每个id。所以我试图想办法以某种方式嵌套case语句来执行每次迭代,而不是迭代所有case语句。

这是我的代码现在花了太长时间的一个例子。

SELECT *,
        CASE WHEN loannumber IN (
            SELECT loannumber FROM PREPAY_LOAN_IDS
        ) THEN 1
        ELSE 0 END AS PREPAY_FLAG,

        CASE WHEN loannumber IN (
            SELECT loannumber FROM DPD_30_IDS
        ) THEN 1    
        ELSE 0 END AS DPD_30_FLAG,

        CASE WHEN loannumber IN (
            SELECT loannumber FROM DPD_60_IDS
        ) THEN 1
        ELSE 0 END AS DPD_60_FLAG,

        CASE WHEN loannumber IN (
            SELECT loannumber FROM DPD_90_IDS
        ) THEN 1    
        ELSE 0 END AS DPD_90_FLAG,

        CASE WHEN loannumber IN (
            SELECT loannumber FROM DPD_120_IDS
        ) THEN 1
        ELSE 0 END AS DPD_120_FLAG,

        CASE WHEN loannumber IN (
            SELECT loannumber FROM FORECLOSURE_IDS
        ) THEN 1    
        ELSE 0 END AS FORECLOSURE_FLAG

FROM(
    SELECT *
    FROM MORTGAGES
    )

2 个答案:

答案 0 :(得分:1)

以下查询将比您发布的查询更快,因为输入表不能完全访问以检索结果。尝试运行此查询并查看其执行情况。

SELECT M.*,
        CASE WHEN PLI.loannumber IS NOT NULL THEN 1
        ELSE 0 END AS PREPAY_FLAG,
        CASE WHEN D3I.loannumber IS NOT NULL THEN 1    
        ELSE 0 END AS DPD_30_FLAG,
        CASE WHEN D6I.loannumber IS NOT NULL THEN 1
        ELSE 0 END AS DPD_60_FLAG,
        CASE WHEN D9I.loannumber IS NOT NULL THEN 1    
        ELSE 0 END AS DPD_90_FLAG,
        CASE WHEN D12I.loannumber IS NOT NULL THEN 1
        ELSE 0 END AS DPD_120_FLAG,
        CASE WHEN FCI.loannumber IS NOT NULL THEN 1    
        ELSE 0 END AS FORECLOSURE_FLAG
  FROM MORTGAGES M
 LEFT JOIN 
       PREPAY_LOAN_IDS PLI
    ON M.loannumber = PLI.loannumber
 LEFT JOIN 
      DPD_30_IDS D3I
    ON M.loannumber = D3I.loannumber 
LEFT JOIN 
       DPD_30_IDS D6I
    ON M.loannumber = D6I.loannumber
 LEFT JOIN 
      DPD_90_IDS D9I
    ON M.loannumber = D9I.loannumber
LEFT JOIN 
       DPD_90_IDS D12I
    ON M.loannumber = D12I.loannumber
 LEFT JOIN 
      FORECLOSURE_IDS FCI
    ON M.loannumber = FCI.loannumber
;

答案 1 :(得分:0)

由于您正在使用SAS,因此这里是一个数据步骤替代方案,假设您的每个数据集已经按loannumber排序或具有索引:

data want;
  merge MORTGAGES(in = Mortgages)
        PREPAY_LOAN_IDS(in = PLIDs keep = loannumber)
        /*etc*/
        ;
  by loannumber;
  if Mortgages;
  PREPAY_FLAG = PLIDs;
  /*etc*/
run;

N.B。如果您在任何其他表中有重复记录,您将从MORTGAGES获得重复记录。