递归跟踪状态数量未知的客户状态 (Presto SQL)
Recursively tracking state of customers with unknown number of states (Presto SQL)
我有一个 table 与我当前的 state_id
客户和另一个 table 持有所有州及其 state_id
,但没有相应的 [=16] =].
但是,历史状态 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
State6 211 226 2017-12-13
State4 226 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 2017-12-13 State6
2 2018-04-01 State4
3 2018-07-10 State3
所以,对于任何 customer_id
,我知道 current_state_id
。有了这个 state_id
,我可以用 replace_state_id
递归地跟踪给定客户所处的所有状态。
我想要一个 table 来显示所有客户以及这些客户历史上所处的所有状态(使用 state_created
列)。未明确给出每个客户所处状态的数量。
数据放在AWS的Athena中,所以语言应该是prestosql
在这里尝试使用递归 CTE:
WITH RECURSIVE cte (state_id, state_name, state_created) AS (
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 cte h2
ON h1.replace_state_id = h2.state_id
)
SELECT
c.customer_id,
t.state_created,
t.state_name
FROM Customer c
INNER JOIN cte t
ON c.current_state_id = t.state_id
ORDER BY
c.customer_id,
t.state_created;
同样,与 中的情况一样,我无法展示 SQLite 的 Rextester 演示,它不支持 SQL 的方言。但是,下面的演示表明递归 CTE 逻辑实际上适用于 SQL 服务器。
我有一个 table 与我当前的 state_id
客户和另一个 table 持有所有州及其 state_id
,但没有相应的 [=16] =].
但是,历史状态 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
State6 211 226 2017-12-13
State4 226 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 2017-12-13 State6
2 2018-04-01 State4
3 2018-07-10 State3
所以,对于任何 customer_id
,我知道 current_state_id
。有了这个 state_id
,我可以用 replace_state_id
递归地跟踪给定客户所处的所有状态。
我想要一个 table 来显示所有客户以及这些客户历史上所处的所有状态(使用 state_created
列)。未明确给出每个客户所处状态的数量。
数据放在AWS的Athena中,所以语言应该是prestosql
在这里尝试使用递归 CTE:
WITH RECURSIVE cte (state_id, state_name, state_created) AS (
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 cte h2
ON h1.replace_state_id = h2.state_id
)
SELECT
c.customer_id,
t.state_created,
t.state_name
FROM Customer c
INNER JOIN cte t
ON c.current_state_id = t.state_id
ORDER BY
c.customer_id,
t.state_created;
同样,与