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

下面的sql语句如何写?
例子:
协议编号                 企业编号         协议类型         有效期至
20060102005             xs002                   计量         2006-05-08
20060709006             xs002                   计量         2007-06-01
20060405001             xs002                   食品         2007-06-02
20070805081             xs002                   食品         2008-06-14
20060205099             dr008                   计量         2006-09-08
20060915799             dr008                   计量         2007-09-08
要求得到如下结果:
20060709006             xs002                   计量         2007-06-01
20060405001             xs002                   食品         2007-06-02
20060915099             dr008                   计量         2006-09-08
即:
相同企业编号的并且相同协议类型的只列出最近的过期协议


------解决方案--------------------
select
t.*
from
表 t
where
t.有效期至 <getdate()
and
not exists(select 1 from 表 where 企业编号=t.企业编号 and 协议类型=t.协议类型)
------解决方案--------------------
select
t.*
from
表 t
where
t.有效期至 <getdate()
and
not exists(select 1 from 表 where 企业编号=t.企业编号 and 协议类型=t.协议类型 and 有效期至> t.有效期至
)
------解决方案--------------------

select *
from table0 a
where 有效期至 < getdate() and
not exists (select 1 from table0 b where b.有效期至 < getdate() and a.企业编号=b.企业编号 and a.协议类型=b.协议类型 and a.有效期至 <b.有效期至 )
------解决方案--------------------
看到头顶了都是闪着,钻石,星星的
只接分好了