表结构
id number 主键
xm varchar2(30) 姓名
xb varchar2(1) y 性别
csrq varchar2(8) y 出生日期
rybs varchar2(2) y 人员标示
zjlx varchar2(30) 身份证件类型
sfzh varchar2(32) 身份证件号码
rygxzl varchar2(3) 人员关系种类
gxpdgz varchar2(3) 关系判别规则
gxfssj varchar2(14) y 关系发生时间
gxfsdd varchar2(255) y 关系发生地点
gxms varchar2(500) y 关系描述
gxfswz varchar2(100) y 关系发生位置
groupid number 组编号
bz varchar2(3000) y 备注
查找内容
通过SFZH查出GROUPID相同的一组人,如果有SFZH和RYGXZL相同的记录,则查出GXFSSJ最近的一条记录,如有最大时间相等的记录取最近一条.
1. 最原始的SQL语句
with a as (select t.*
from scsjgx.zdrygxxx t
where exists (select groupid
from scsjgx.zdrygxxx a
where t.groupid = a.groupid
and a.sfzh = '51113319711226*****')
and gxpdgz <> 0)
select * from scsjgx.zdrygxxx b where
gxfssj = (select max(gxfssj)
from a
where b.sfzh = a.sfzh
and b.rygxzl = a.rygxzl)
order by rygxzl, sfzh;
2.第一次优化后的语句
select t.*
from scsjgx.zdrygxxx t
where gxfssj = (select max(gxfssj) from (select t.*
from scsjgx.zdrygxxx t
where exists (select groupid
from scsjgx.zdrygxxx a
where t.groupid = a.groupid
and a.sfzh = '5111331971122****')
and gxpdgz <> 0)
where sfzh = t.sfzh
and rygxzl = t.rygxzl)
and gxpdgz <> 0
order by t.rygxzl, t.sfzh;
3.最后的语句(去除有两个最大时间的记录)
select t.*
from scsjgx.zdrygxxx t
where (gxfssj,rowid) = (select max(gxfssj),max(rowid)
from (select t.*
from scsjgx.zdrygxxx t
where exists (select groupid
from scsjgx.zdrygxxx a
where t.groupid = a.groupid
and a.sfzh = '5111331971122****')
and gxpdgz <> 0)
where sfzh = t.sfzh
and rygxzl = t.rygxzl)
and gxpdgz <> 0
order by t.rygxzl, t.sfzh;
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/16298743/viewspace-1057038/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/16298743/viewspace-1057038/