表的两列之间的序列的最终成员

时间:2018-10-18 09:29:16

标签: sql exasolution

我有一个表,该表主要包含3列我感兴趣的列:old_item_idnew_item_iddate_of_change。我想遍历该序列,并希望找出某些项目ID的最新id。下面的示例数据:

old_item_id new_item_id date_of_change
     1            2        2015-01-01
     2            5        2015-01-02
     5            12       2015-10-01
     4            5        2015-01-02
     6            7        2015-02-02

因此,如果我想要第1、4、6和8条的最新ID,在这种情况下,我应该得到以下输出:

item_id    latest_item_id 
     1            12               
     4            12        
     6            7
     8            8

因为可以将1和4追溯到12。将项目ID 6更改为7,并且将项目ID 8从未更改。

当前,我是通过在另一个脚本的while循环中反复打表来实现此目的的。但是我正在寻找查询以在单个数据库命中中做到这一点。

1 个答案:

答案 0 :(得分:2)

这可以通过软件包igraph完成,但这是一种图论解决方案,而不是数据库解决方案。

library(igraph)

g <- graph_from_data_frame(dat)
res <- lapply(V(g), function(i) dfs(g, i, unreachable = FALSE)$order)
res <- lapply(res, function(e) e[!is.na(e)])
sapply(res, function(e) names(e)[length(e)])
#   1    2    5    4    6   12    7 
#"12" "12" "12" "12"  "7" "12"  "7"

请注意,如果需要,您可以将最终结果强制为integer类。

数据。

dat <-
structure(list(old_item_id = c(1L, 2L, 5L, 4L, 6L), new_item_id = c(2L, 
5L, 12L, 5L, 7L), date_of_change = structure(c(16436, 16437, 
16709, 16437, 16468), class = "Date")), row.names = c(NA, -5L
), class = "data.frame")