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

高手来看看这个sql的数据查询问题! 急等!
字段结构如下:
id bh jine pzsj
26 1002 13 2011-8-12
27 1005 33 2011-8-3
28 1005 25 2011-8-3
29 1003 18 2011-8-4
30 1004 59 2011-8-16
31 1004 89 2011-8-12
32 1005 29 2011-8-3
33 1004 19 2011-8-2

id自动增长;bh为编号 jine为金额 pzsj 为批准时间,现在要求如下:
1、同一编号如1005 批准时间也是一样的话,则取id号最新的那条
2、同一编号如1004 批准时间不同,则取批准时间最新的那条
3、按编号排序

如此例:结果应该要这样:
id bh jine sj
26 1002 13 2011-8-12
29 1003 18 2011-8-4
30 1004 59 2011-8-16 (因为1004的时间不同,所以取批准时间最新的日期的那条记录)
32 1005 29 2011-8-3 (因为1005同一天批准,所以去id号最大的那条记录)

求用一条sql语句,写出这样的数据过滤查询来!高手请帮忙!





------解决方案--------------------
SQL code

select *
from tb t
where not exists (select 1 from tb where bh=t.bh and (pzsj>t.pzsj or (pzsj=t.pzsj and id>t.id)))

------解决方案--------------------
SQL code
select * from tb where id in (select max(id) from tb group by bd,pzsj)

------解决方案--------------------
SQL code

select *
from tb t
where id = (select top 1 id from tb where bh=t.bh order by pzsj desc,id desc)

------解决方案--------------------
SQL code
select
 *
from
 tb t
where
 not exists (select 1 from tb where bh=t.bh and (pzsj>t.pzsj or (pzsj=t.pzsj and id>t.id)))