簡體   English   中英

在SAS EG proc SQL中循環數據集

[英]Loop for dataset in SAS EG proc SQL

我是SAS EG的新手,我想知道如何通過基於SAS EG中三列值的循環來追加數字。 例如。

Column0 Column1 Column2 Level(期望的結果)1A AA 0 1A 123AA AA 1 1A 234AA 123AA 2 2B BB 0 2B 123BB BB 1 2B 234BB BB 1 2B 345BB 123BB 2 2B 456BB 345BB 3

想知道是否有任何方法可以在同一個表上執行vlookup並添加新列以將結果數據存儲在同一個表中?

SQL不知道存儲在磁盤上的行的順序,並且您的數據沒有可用於指向SORTED BY的值的附加列。

DATA步驟提供了一種更簡單的方法,其中行序列為“讀取”。 由column1鍵入的哈希對象可以保持先前行的級別值,而column2可以用作查找的鍵值。

例如:

data have;
infile datalines missover;
input
Column0 $ Column1 $ Column2 $; datalines;
1A        AA             
1A        123AA     AA   
1A        234AA     123AA
2B        BB             
2B        123BB     BB   
2B        234BB     BB   
2B        345BB     123BB
2B        456BB     345BB
run;

data want;

  set have;
  by column0;

  if _n_ = 1  then do;
    declare hash lookup();
    lookup.defineKey('column1');
    lookup.defineData('level');
    lookup.defineDone();
  end;

  if first.column0 then
    lookup.Clear();

  if (lookup.find(key:column2) ne 0) then
    level = 0;
  else
    level + 1;

  lookup.add();
run;

注意:上述方法可能需要調整才能在VIYA中使用。

在SQL中執行相同操作需要多個步驟。 為適當的孩子計算(或發現)每個級別一步。

proc sql;
  create table level0 as
  select child.*, 0 as level from have as child
  where child.column2 is null;

  %put &=SQLOBS;

  create table level1 as
  select child.*, 1 as level from level0 as parent join have as child
  on parent.column0 = child.column0 and child.column2 = parent.column1;

  %put &=SQLOBS;

  create table level2 as
  select child.*, 2 as level from level1 as parent join have as child
  on parent.column0 = child.column0 and child.column2 = parent.column1;

  %put &=SQLOBS;

  create table level3 as
  select child.*, 3 as level from level2 as parent join have as child
  on parent.column0 = child.column0 and child.column2 = parent.column1;

  %put &=SQLOBS;

  create table level4 as
  select child.*, 4 as level from level3 as parent join have as child
  on parent.column0 = child.column0 and child.column2 = parent.column1;

  %put &=SQLOBS; * 0 obs, so no more children needing parentage found;

  create table want as
  select * from level0 union 
  select * from level1 union
  select * from level2 union
  select * from level3 
  order by column0, level
  ;

通用方法必須循環,直到SQLOBS為0

  create table level&LOOPINDEX as
  select child.*, &LOOPINDEX as level 
  from level&LOOPINDEX_MINUS_1 as parent 
  join have as child
  on parent.column0 = child.column0 and child.column2 = parent.column1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM