我有以下2个表格:
MATERIALIZED VIEW
我希望将Table1中的时间戳与表2中最接近的先前登录相匹配,其中IP是相同的,以便获得登录的用户。所以结果应该是这样的:
Table1 Table2
ID IP Timestamp IP Login User
1 10.2.4.8 02/04/2016 9.10 10.2.4.8 01/04/2016 8.20 Green
2 10.2.4.8 02/04/2016 13.50 10.2.4.8 01/04/2016 8.50 Blue
3 10.20.3.5 02/04/2016 13.59 10.2.4.8 02/04/2016 9.20 Red
4 10.2.4.8 03/04/2016 10:25 10.20.3.5 04/04/2016 11:25 Blue
5 10.20.3.5 04/04/2016 11:25 10.20.3.5 01/04/2016 10:25 Yellow
我正在使用SQL.Thanks获取任何帮助
我想出的解决方案是:
ID IP Timestamp User
1 10.2.4.8 02/04/2016 9.10 Blue
2 10.2.4.8 02/04/2016 13.50 Red
3 10.20.3.5 02/04/2016 13.59 Yellow
4 10.2.4.8 03/04/2016 10:25 Red
5 10.20.3.5 04/04/2016 11:25 Blue
我不确定它是否正确,以及是否有更好的解决方案。谢谢
答案 0 :(得分:1)
这是使用correlated subquery
与top
:
select t.id, t.ip, t.timestamp,
(select top 1 t2.user
from table2 as t2
where t.ip = t2.ip
and t2.timestamp < t.timestamp
order by t2.timestamp desc) as user
from table1 as t