递归跟踪客户状态(Presto SQL)

Recursively tracking state of customers (Presto SQL)

我有一个 table 与我当前的 state_id 客户和另一个 table 持有所有州及其 state_id,但没有相应的 [=31] =].但是,历史状态 table 保留了它所替换的 state_id 的信息。因此,应该可以递归地跟踪客户的states/journey。

考虑以下示例:

"Customer" table:

customer_id    state_created      current_state_id
1              2017-11-09         33
2              2018-04-01         243
3              2018-07-10         254

"Historical_state" table:

state_name     replace_state_id   state_id           state_created
State1                            22                 2015-10-08
State1                            211                2017-06-28
State3                            254                2018-07-10
State4         211                243                2018-04-01
State5         22                 33                 2017-11-09

我有兴趣获取每个客户的历史状态信息,即。以下 table:

customer_id    state_created      state_name       
1              2015-10-00         State1
1              2017-11-09         State5
2              2017-06-28         State1
2              2018-04-01         State4
3              2018-07-10         State3

数据在AWS的Athena中被替换,所以应该使用presto sql作为语言。

这是一个使用联合的选项。此查询背后的症结在于我们生成了一个逻辑 state_id 列,我们将客户 table 加入其中。此 table 包含给定状态的当前和替换 state_id 值。

SELECT
    c.customer_id,
    t.state_created,
    t.state_name
FROM Customer c
INNER JOIN
(
    SELECT state_id, state_name, state_created
    FROM Historical_state
    UNION ALL
    SELECT h1.state_id, h2.state_name, h2.state_created
    FROM Historical_state h1
    INNER JOIN Historical_state h2
        ON h1.replace_state_id = h2.state_id
) t
    ON c.current_state_id = t.state_id;

这里有一个demo在MySQL,因为Rextester不支持SQLite,但至少说明查询逻辑是正确的

Demo