[英]SQL to compare records (status change) in table
我有一张包含索赔历史的表格。 基本上我在看状态变化和日期。 每当有人更新声明时,新行都会加载到我在下面显示的表格中。 我想要获得的是“c_sta_clm”列的所有状态更改我希望能够捕获日期“row_begin_dt”并且状态更改(PC到AC)和(AC到TE)。
任何关于如何使这个简单的指导非常感谢。 我正在考虑制作两个易失性表并加入C_CLM,获取最小状态日期并比较等...
row_begin_dt user c_clm c_sta_clm
2009-10-08 ? C5S2M 09050012 PC
2009-10-24 ? C5S2M 09050012 AC
2009-10-28 ? C1CMH 09050012 AC
2010-10-30 ? C1CMH 09050012 AC
2011-05-19 ? A9709 09050012 AC
2011-06-09 ? C6JEC 09050012 AC
2011-10-07 ? DAJ07 09050012 TE
2011-11-04 ? DAJ07 0905001 TE
这应该可以获得2009-10-24和2011-10-07的记录。
select
row_begin_dt,
user,
c_clm,
c_sta_clm,
-- Find the c_sta_clm of the previous row
max(c_sta_clm) over (partition by c_clm order by row_begin_dt rows between 1 preceding and 1 preceding) as prev_c_sta_clm
from claims
-- Include only records which have a c_sta_clm different to that of the previous row
qualify c_sta_clm <> prev_c_sta_clm
一种通用的方法是使用相关子查询:
select
from (select c.*,
(select top 1 from claims c2 where c2.c_clm = c.c_clm a and c2.row_begin_dt > c.row_begin_dt order by row_begin_dt
) as next_sta_clm
from claim c2
) c
where next_sta_clm <> c_sta_clm
在许多数据库中,您可以使用lag
或lead
函数执行相同的操作,但并非所有数据库都支持它们。
就像是
Select ToRecord.row_begin_dt From ClaimHistory FromRecord
inner join ClaimHistory ToRecord On ToRecord.c_clm = FromRecord.c_clm and ToRecord.row_begin_dt > FromRecord.row_begin_dt and ToRecord.c_sta_claim = 'AC'
Where FromRecord.c_sta_claim = 'PC'
将PC送到AC,不知道用户列是否显着,但是将其固定应该是微不足道的。 看你没有说哪个DBMS,sql可能需要一个旋转。
此外,这将拿起像PC到XX到AC的东西,你没有说什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.