我有以下场景,我能想到的唯一方法是将所有数据拉回临时表,然后使用游标循环遍历它,根据当前记录更新记录或最后一条记录。
基本上,如果发生称为澄清的操作,我想返回此记录,但如果在澄清之后发生澄清保留,那么我不希望返回澄清。
现在的问题是,在没有澄清保留的情况下,任何数量的澄清都可能连续发生,所以如果发生 5 次澄清,然后有 1 次保留,我想返回 4 条记录。保留之后也可以进行澄清,在这种情况下,我想显示澄清。
有人对比光标更好的解决方案有任何建议吗?
我有以下场景,我能想到的唯一方法是将所有数据拉回临时表,然后使用游标循环遍历它,根据当前记录更新记录或最后一条记录。
基本上,如果发生称为澄清的操作,我想返回此记录,但如果在澄清之后发生澄清保留,那么我不希望返回澄清。
现在的问题是,在没有澄清保留的情况下,任何数量的澄清都可能连续发生,所以如果发生 5 次澄清,然后有 1 次保留,我想返回 4 条记录。保留之后也可以进行澄清,在这种情况下,我想显示澄清。
有人对比光标更好的解决方案有任何建议吗?
我已经对您的数据结构做出了假设,但该理论仍应适用于您
-- Example table
DECLARE @t table (
action_description char(20)
, when_occured datetime
);
-- Set up data
INSERT INTO @t (action_description, when_occured)
VALUES ('clarification' , DateAdd(mi, -9, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -8, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -7, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -6, Current_Timestamp))
, ('clarification hold', DateAdd(mi, -5, Current_Timestamp))
, ('clarification' , DateAdd(mi, -4, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -3, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -2, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, -1, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, 0, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, +1, Current_Timestamp))
, ('clarification hold', DateAdd(mi, +2, Current_Timestamp))
, ('clarification' , DateAdd(mi, +3, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, +4, Current_Timestamp))
, ('clarification hold', DateAdd(mi, +5, Current_Timestamp))
, ('clarification hold', DateAdd(mi, +6, Current_Timestamp))
, ('clarification' , DateAdd(mi, +7, Current_Timestamp)) -- Include
, ('clarification' , DateAdd(mi, +8, Current_Timestamp))
, ('clarification hold', DateAdd(mi, +9, Current_Timestamp));
; WITH all_actions AS (
SELECT action_description
, when_occured
, Row_Number() OVER (ORDER BY when_occured) As row_num -- Provide a sequence for joining
FROM @t
)
SELECT a1.action_description
, a1.when_occured
FROM all_actions As a1
LEFT
JOIN all_actions As a2 -- Join back to self
ON a2.row_num = a1.row_num + 1 -- on previous row
AND a2.action_description = 'clarification hold' -- where the previous row had this action
WHERE a1.action_description = 'clarification' -- Only want to show clarification actions
AND a2.action_description IS NULL -- and exclude those who had a row in the join