日期:2014-05-18  浏览次数:20688 次

时间比较问题
数据库设计

id   开始时间   结束时间   证件号码


要求,同一个证件号码,在开始时间和结束时间中,有叠加的不超过3次

如:
1   2007-02-10   2007-07-10
2   2007-04-10   2007-08-10
3   2007-06-10   2007-12-10

这三个时间段中,
1   /   2   /3  
6/7月份是3个都有的,那么,这就是非法的


------解决方案--------------------
前不久刚写过一个类似的
select * from your_table
where crd_no in (
select crd_no from (
SELECT aa.crd_no as crd_no, count(aa.crd_no) as dup_count
FROM your_table aa, your_table bb
WHERE aa.crd_no = bb.crd_no
AND aa.id <> bb.id
AND ( (aa.start_date between bb.start_date and bb.end_date)
OR (bb.start_date between aa.start_date and aa.end_date)
)
group by aa.crd_no having count(aa.crd_no) < 3
)
)
大文字的是我写的用来check重复纪录的,小文字是根据LZ要求加的,没测试过,LZ自己测一下吧

------解决方案--------------------
补充:我的表是日期类型的,LZ的如果是文字类型可以通过to_date转换一下,但如果文字长度一样,文字类型也是可以直接比较的