如何用SAS Proc SQL实现无重复内连接带时间戳的两张表?
解决SAS Proc SQL内连接避免重复行的问题
嘿,我来帮你搞定这个Proc SQL连接后出现重复行的问题~
首先咱们明确问题根源:你现在用datepart(table1.date)=datepart(table2.date)来连接,会把同一天同一id、tag的所有记录都互相匹配,自然就产生了重复。而你的实际需求是table1的每条交易开始记录,对应table2里同id、tag且时间上对应的交易结束记录,比如00:04的开始对应00:06的结束,00:09的开始对应00:10的结束。
先把你提供的表结构清晰展示出来:
原始表结构
Table1
id tag date amount name_x 1 23 01JUL2018:00:04 12 smith ltd 1 23 01JUL2018:00:09 12 anna smith
Table2
id tag ref amount date 1 23 19 12 01JUL2018:00:06:00 1 23 20 12 01JUL2018:00:10:00
解决方案
下面给你两种高效的方法,根据你的实际场景选择:
方法一:按时间顺序添加行号匹配(适合记录数严格一一对应)
如果同一id、tag下,两张表的记录数一致,且时间顺序是一一对应的,这种方法效率最高:
proc sql; create table desired_output as select t1.id, t1.tag, datepart(t1.date) as date format=date9., t1.amount, t1.name_x, t2.ref from ( /* 给table1按id、tag、时间排序,添加行号 */ select *, row_number() over(partition by id, tag order by date) as rn from table1 ) t1 inner join ( /* 给table2按同样规则添加行号 */ select *, row_number() over(partition by id, tag order by date) as rn from table2 ) t2 on t1.id = t2.id and t1.tag = t2.tag and t1.rn = t2.rn; /* 通过行号精准匹配对应行 */ quit;
方法二:精准时间匹配(适合灵活场景)
如果某天可能有多条记录,或者需要确保table2的时间晚于table1的交易时间,用这种方法更稳妥:
proc sql; create table desired_output as select t1.id, t1.tag, datepart(t1.date) as date format=date9., t1.amount, t1.name_x, t2.ref from table1 t1 inner join table2 t2 on t1.id = t2.id and t1.tag = t2.tag and t2.date > t1.date /* 确保table2是交易结束时间,晚于开始时间 */ /* 子查询找到当前table1记录对应的最早的table2结束记录 */ where t2.date = ( select min(date) from table2 where id = t1.id and tag = t1.tag and date > t1.date ); quit;
两种方法都能得到你想要的输出:
id tag date amount name_x ref 1 23 01JUL2018 12 smith ltd 19 1 23 01JUL2018 12 anna smith 20
内容的提问来源于stack exchange,提问作者anna
相关产品推荐
相关产品推荐

