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

一个你们觉得不难的查询,急用,请帮忙!
有一个表[犯人],表中有字段“监狱编码”,“添加时间”,“在押男人数”,“在押女人数”

其中“监狱编码”,“添加时间”共同构成主建

每天各个监狱都会向这个表中添加新的数据,并不覆盖任何数据。

现在我想显示一个表,四个字段均显示在表中,表中每个监狱只有一条记录,并且这条记录是最新添加进去的。

看了半天书还是不会,上来求救各位!

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

Select * from 表 as t
where not exists(Select * from 表
  Where 监狱编码=t.监狱编码 and 添加时间>t.添加时间)

------解决方案--------------------
select a.* from tb a,
(select 监狱编码 , max(添加时间) 添加时间 from tb group by 监狱编码) b
where a.监狱编码 = b.监狱编码 and a.添加时间 = b.添加时间
------解决方案--------------------
SQL code
多种方法。

还可以按监狱编码分组,求添加时间最大值,然后再与原表关联。

select a.* 
from tb as a 
   inner join (select 监狱编码,max(添加时间) 添加时间 from tb group by 监狱编码) as b on a.监狱编码 = a.监狱编码 and a.添加时间=b.添加时间

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

Select * from 表 as t
where t.添加时间 = (Select max(添加时间) from 表 group by 监狱编码)

------解决方案--------------------
Select * from Table T1 INNER JOIN (Select 监狱编码, MAX(添加时间) 添加时间 FROM Table group by 监狱编码) T2 On T1.监狱编码 = T2.监狱编码 and T1.添加时间 = T2.添加时间

------解决方案--------------------
declare @犯人 table(监狱编码 int,在押男人数 int ,在押女人数 int,添加时间 datetime)
insert into @犯人 select 4321,21,23,'2007-10-11'
insert into @犯人 select 4322,22,24,'2007-10-11'
insert into @犯人 select 4323,21,23,'2007-10-11'

insert into @犯人 select 4321,21,23,'2007-10-10'
insert into @犯人 select 4322,22,24,'2007-10-10'
insert into @犯人 select 4323,21,23,'2007-10-10'

insert into @犯人 select 4321,20,21,'2007-10-09'
insert into @犯人 select 4322,21,21,'2007-10-09'
insert into @犯人 select 4323,20,21,'2007-10-09'



select 监狱编码,在押男人数,在押女人数,max(添加时间)
from @犯人
where cast(监狱编码 as varchar(10))+cast(在押男人数 as varchar(10))+cast(在押女人数 as varchar(10)) in
(select max(cast(监狱编码 as varchar(10))+cast(在押男人数 as varchar(10))+cast(在押女人数 as varchar(10)))
from @犯人
group by 监狱编码)
group by 监狱编码,在押男人数,在押女人数


我得完全正确,可以给我分了.