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

求一个SQL语句,请指点一下!!!!
Sql 中有这样一张表A:

ID CONTENT TIME TYPE

001 XXXX 2005-01-01 新闻
002 XXXX 2005-01-09 新闻
003 XXXX 2005-01-10 新闻
004 XXXX 2005-03-01 新闻
005 XXXX 2005-04-14 新闻
006 TTTTT 2006-02-01 供求
007 TTTTT 2006-01-01 供求
008 RRRRR 2006-01-20 供求
009 QQQQQ 2006-03-01 IT
…………………………

我现在想要查询出每一个类(TYPE)中,时间(TIME)最晚的2条记录,及下面这样的结果:

ID CONTENT TIME TYPE

005 XXXX 2005-04-14 新闻
004 XXXX 2005-03-01 新闻
006 TTTTT 2006-02-01 供求
008 RRRRR 2006-01-20 供求
………………………………

请问这样的SQL语句怎么写,请指点一下,谢谢!!

学习,关注!!!!





------解决方案--------------------

select * from A as t1 where (select count(1) from A where Type=t1.Type and ID!>A.ID)!>2

或用时间做为判断(时间类型是datetime可用)
select * from A as t1 where (select count(1) from A where Type=t1.Type and TIME!>A.TIME)!>2
------解决方案--------------------
--建立环境

if object_id('a')>0 drop table a
go
create table a(id varchar(10),content varchar(20),time datetime,type varchar(20))
insert into a
 select '001', 'XXXX', '2005-01-01', '新闻' 
union all select '002', 'XXXX', '2005-01-09', '新闻' 
union all select '003', 'XXXX', '2005-01-10', '新闻' 
union all select '004', 'XXXX', '2005-03-01', '新闻' 
union all select '005', 'XXXX', '2005-04-14', '新闻' 
union all select '006', 'TTTTT', '2006-02-01', '供求' 
union all select '007', 'TTTTT', '2006-01-01', '供求' 
union all select '008', 'RRRRR', '2006-01-20', '供求' 
union all select '009', 'QQQQQ', '2006-03-01', 'IT' 


go
 
----按time排序

if object_id('temp') is not null drop table temp
select * into temp from a order by type,time 
 
go

--执行:

select * from temp b where (select count(id) from temp where id>=b.id and type=b.type )<=2 order by id


/*
结果:
id content time type
------------------------------------------------------
004 XXXX 2005-03-01 00:00:00.000 新闻
005 XXXX 2005-04-14 00:00:00.000 新闻
007 TTTTT 2006-01-01 00:00:00.000 供求
008 RRRRR 2006-01-20 00:00:00.000 供求
009 QQQQQ 2006-03-01 00:00:00.000 IT
*/



 
 
------解决方案--------------------
select * from A t
where TIME in 
(
select top 2 TIME from A where TYPE =t.TYPE order by TIME desc
)
------解决方案--------------------
select * from A t
where (select count(*) from A where TYPE = t.TYPE and time > t.time) < 2
------解决方案--------------------
该成这样的可以不?
select * from A t 
where TIME in ( 
select top 2 TIME from A group by type order by TIME desc ) 
不行,查询中做了分组或者聚合运算,则在结果集中只能出现进行分组的字段和聚合函数

建议使用
select * from test as t where id in ( select top 2 id from test where type=t.type order by time desc )


------解决方案--------------------
哦。谢谢了楼上了。我知道错在那里了。
还有这个是不是自连接。就是说表自己和自己连接的呢?