我有这样一张表:
CustName Country RecordedTime --------------------------------------------- Alex Australia 2018-Jun-01 08:00 AM Alex China 2018-Jun-01 10:00 AM Alex Japan 2018-Jun-01 11:00 AM John Australia 2018-Jun-01 08:00 AM John China 2018-Jun-02 08:00 AM Bob Australia 2018-Jun-02 09:00 AM Bob Brazil 2018-Jun-03 09:50 AM
如果记录是系统中的全新记录,则该记录应在给定日期的“审核”和“历史记录”字段(结果集中的两个附加字段)中显示“ ADD”和“ NEW”。
如果该记录当天被编辑过两次,则在给定日期,应在审核字段中分别显示两个带有“ ADD”和“ CHANGE”的条目,在“历史记录”状态字段中显示“ BEFORE”和“ CURRENT”。
例如,这就是我的结果应如何显示;
当我将输入日期传递为2018年6月1日时,输出应如下所示:
CustName Country RecordedTime Audit History ---------------------------------------------------------------- Alex Australia 2018-Jun-01 08:00 AM ADD NEW Alex China 2018-Jun-01 10:00 AM CHANGE BEFORE Alex Japan 2018-Jun-01 11:00 AM CHANGE CURRENT John Australia 2018-Jun-01 08:00 AM ADD NEW
当我将输入日期传递为2018年6月2日时,输出应如下所示:
CustName Country RecordedTime Audit History ----------------------------------------------------------------- John China 2018-Jun-02 08:00 AM CHANGE CURRENT Bob Australia 2018-Jun-02 09:00 AM ADD NEW
CustName Country RecordedTime Audit History ---------------------------------------------------------------- Bob Brazil 2018-Jun-03 09:50 AM CHANGE CURRENT
我尝试了许多方法,但仍然缺少实现这一目标的一些方案。有人可以说明一下吗?
一种实现方法是通过如下所示的cte,其中我们具有row_number()函数来双向跟踪序列。
看 **[live demo](http://rextester.com/VYAJ64788)**
**[live demo](http://rextester.com/VYAJ64788)**
; with cte as ( select *, rn= row_number() over(partition by CustName order by RecordedTime), rn2=row_number() over(partition by CustName order by RecordedTime desc) from records ) , cte2 as ( select *, audit='New', History='Change' from cte where rn=1 union select *, audit='Change', History='Current' from cte where rn2=1 and rn<>1 union select *, audit='Change', History='before' from cte where rn>1 and rn2<>1 ) select CustName, Country, RecordedTime, audit, History from cte2 order by CustName,RecordedTime