【问题标题】:SAS proc sql inner join without duplicatesSAS proc sql内部连接没有重复
【发布时间】:2018-05-14 15:19:17
【问题描述】:

我正在努力在不使用 proc sql 创建重复行的情况下加入两个表(不确定是否有任何其他方法更有效)。

内部连接开启:datepart(table1.date)=datepart(table2.date) AND tag=tag AND ID=ID

我认为问题在于表 1 中的日期和不同的名称。通过查看该表,很清楚 table1 的第 1 行应该与表 2 的第 1 行连接,因为事务在表 1 的 00:04 开始并在表 2 中的 00:06。我遇到的问题是我无法加入带有时间戳的日期,因此我正在删除时间戳,因此它会创建重复项。

Table1:

id tag    date            amount   name_x
1 23      01JUL2018:00:04  12          smith ltd
1 23      01JUL2018:00:09  12          anna smith



table 2:



id tag  ref   amount   date
1 23   19   12          01JUL2018:00:06:00
1 23   20   12          01JUL2018:00:10:00



Desired output:

id tag    date            amount   name_x       ref
1 23      01JUL2018  12          smith ltd       19
1 23      01JUL2018  12          anna smith      20

感谢您的帮助。 谢谢!

【问题讨论】:

    标签: sas proc-sql


    【解决方案1】:

    您需要为该日期时间连接设置边界。你为什么会得到重复是正确的。我猜下限是以前的日期时间,如果它存在并且上限是这条记录的日期时间。

    顺便说一句,这对某人来说是糟糕的数据库设计......

    让我们先按idtagdate 对表2 进行排序

    proc sort data=table2 out=temp;
    by id tag date;
    run;
    

    现在编写一个数据步骤,为唯一的id/tag 组合添加上一个日期。

    data temp;
    set temp;
    format low_date datetime20.
    by id tag;
    retain p_date;
    
    if first.tag then
       p_date = 0;
    
    low_date = p_date;
    p_date = date;
    run;
    

    现在更新您的加入以使用日期范围。

    proc sql noprint;
    create table want as
    select a.id, a.tag, a.date, a.amount, a.name_x, b.ref
    from table1 as a
      inner join
         temp as b
      on a.id = b.id
      and a.tag = b.tag
      and b.low_date < a.date <= b.date;
    quit;
    

    【讨论】:

      【解决方案2】:

      如果我的理解是正确的,你想通过ID,标签和最接近的两个日期进行合并,这意味着table1中的01JUL2018:00:04与talbe2中的01JUL2018:00:06:00和01JUL2018最接近: 00:09 是 01JUL2018:00:10:00,你可以试试这个:

      data table1;
      input id tag date:datetime21.   amount   name_x $15.;
      format date datetime21.;
      cards;
      1 23 01JUL2018:00:04 12 smith ltd
      1 23 01JUL2018:00:09 12 anna smith
      ;
      
      data table2;
      input id tag  ref   amount   date: datetime21.;
      format date datetime21.;
      cards;
      1 23 19 12 01JUL2018:00:06:00
      1 23 20 12 01JUL2018:00:10:00
      ;
      
      
      proc sql;
         select a.*,b.ref from table1 a inner join table2 b
         on a.id=b.id and a.tag=b.tag
         group by a.id,a.tag,a.date
         having abs(a.date-b.date)=min(abs(a.date-b.date));
      quit;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多