数据库中带时间戳数据总结

数据库中带时间戳数据总结

数据库已经运用越来越广泛,数据表中带时间的数据记录也越来越常见,下面对数据表中一种类似”历史演变情况“数据集进行一系列的总结,供自己参考,供别人分享,一起学习进步。
第一(背景):什么是带时间戳的数据表结构(下面简称历史演变数据)
举例一种通人员履历记录(history)
主键id 人员(staf_id) 单位或学校(comp_id) 开始时间(startdate) 工作岗位(post) 薪水(salary)/每天
1 s1 c1 2011-11-11 p1 100
2 s2 c2 2012-12-12 p2 200
3 s1 c3 2013–01-01 p3 300
4 s3 c1 2010-10-10 p4 222

1000000 s888 c666 2017-03-16 p1 1111
第二(定义)类似于上面。。。。。。。。。。。。定义为历史演变数据
第三(操作)
为了方便操作:创建一张带终止日期的视图(v_history)
create view as select a.*,(select min(startdate) from history where startdate>a.startdate) as enddate from history a
(1) 查询所有人员的当前薪水
a:select salary from history a where startdate = (select max(startdate) from history where staf_id = a.staf_id)
b:select salary from v_history a where endate is null
(2)查询所有人在某个时间dd的所有信息
A: select salary from history a where startdate = (select max(startdate) from history where staf_id = a.staf_id and startdate B; select salary from history a where startdate

dd
(3)查询某人的前后薪水对比情况
A: select salary,(
select salary from history b where b.staf_id = a.staf_id and b.startdate=
(select min(startdate) from history c where c.staf_id = a.staf_id and startdate>a.startdate)
)as salary2 from history a
问题扩展,如果同一天存在两条记录如何处理
需求:按照id作为第二的规则(相同一天的情况将取id较大的记录,系统默认时间戳排序之后id排序)
select salary,(
select salary from history b where b.staf_id = a.staf_id and b.id=
(select max(id) from history c where c.staf_id = a.staf_id and c.startdate= (
select min(startdate) from history d where d.staf_id = a.staf_id and d.startdate>a.startdate)
)
)as salary2 from history a

   select  salary,(
             select salary from history b where b.staf_id = a.staf_id and (b.startdate||b.id)=
                    (select max(startdate||id) from history c where c.staf_id = a.staf_id and c.startdate>a.startdate)
                     )
   )as salary2 from history a  

你可能感兴趣的:(数据库中带时间戳数据总结)