gpt4 book ai didi

mysql - 跟踪当前和以前的状态

转载 作者:行者123 更新时间:2023-11-29 00:11:01 26 4
gpt4 key购买 nike

我有一个表,它保存与 process_id 相对应的 statuscreated_timestamp。一旦进程状态发生变化,就会插入一行。因此,具有相同 process_id 的行的数量与与其相关联的状态的数量一样多。我想使用此数据创建另一个表/ View ,其中一行对应于一个process_id、它的当前状态和它以前的状态。我需要为此创建一个 Informatica 作业,但 SQL 查询也同样有用。
示例输入:

Process_id | Status     | Created 
1 | In_queue | 2014-08-01 00:01:01
1 | Started | 2014-08-01 01:03:01
1 | In_process | 2014-08-01 01:50:20
1 | Complete | 2014-08-01 03:10:20

Sample Output:
Process_id | Previous_status | Current_status | Updated
1 | In_process | Complete | 2014-08-01 03:10:20

最佳答案

SELECT Process_id, Previous_status, Current_status, Updated 
FROM (
SELECT
Process_id,
Status AS Current_status,
Created AS Updated,
@prev_state AS Previous_status,
@prev_state := Status
FROM
your_table t
, (select @prev_state := null) var_init
WHERE Process_id = 1
ORDER BY Created
) sq

更新:

要为所有 Process_id 执行此操作并仅获取每个 Process_id 的最新记录,您可以使用此方法:

SELECT sq.Process_id, sq.Previous_status, sq.Current_status, sq.Updated 
FROM (
SELECT
Process_id,
Status AS Current_status,
Created AS Updated,
@prev_state := if(@prev_process != Process_id, null, @prev_state),
@prev_state AS Previous_status,
@prev_state := Status,
@prev_process := Process_id
FROM
your_table t
, (select @prev_state := null, @prev_process := null) var_init
ORDER BY Process_id, Created
) sq
INNER JOIN (
SELECT Process_id, MAX(Created) AS max_created
FROM your_table
GROUP BY Process_id
) max_c
ON sq.Process_id = max_c.Process_id AND sq.Updated = max_c.max_created

关于mysql - 跟踪当前和以前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com