急!!! 这个SQL该怎么写?马上结贴
以下用SQL能实现吗?如何实现?
表A结构及测试数据如下:
id subject cati
----------------------
1 是非功过 1
2 有在世界 2
3 地区性要 3
4 国营农场 1
5 不堪重负 3
6 这一点上 2
7 要不是地 3
8 中草药在 1
9 是非国营 2
10 为不堪重 1
11 工期地区 3
目的:各分类cati取出前两条数据(按ID降序),结果如下:
id subject cati
----------------------
10 为不堪重 1
8 中草药在 1
9 是非国营 2
6 这一点上 2
11 工期地区 3
7 要不是地 3
问题点数:0、回复次数:9Top
1 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-04-02 15:31:44 得分 0
select
a.*
from
表A a
where
id in(select top 2 id from 表A where cati = a.cati order by id desc)
order by
cati,id descTop
2 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-04-02 15:32:25 得分 0
select
a.*
from
表A a
where
a.id in(select top 2 id from 表A where cati = a.cati order by id desc)
order by
a.cati,a.id descTop
3 楼paoluo(一天到晚游泳的鱼)回复于 2005-04-02 15:42:33 得分 0
select * from 表A a
where id in (select top 2 id from 表A where cati = a.cati order by id desc)
order by cati,id desc
Top
4 楼dgseamaple(笨牛(我很笨但是我很勤奋))回复于 2005-04-02 16:19:04 得分 0
libin_ftsafe(子陌红尘) 的结果为:
10 为不堪重 1
11 工期地区 3Top
5 楼dgseamaple(笨牛(我很笨但是我很勤奋))回复于 2005-04-02 16:19:46 得分 0
paoluo(一天到晚游泳的鱼) 的也是一样,不行的。Top
6 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-04-02 16:29:25 得分 0
--生成测试数据
create table t(
id int,
subject varchar(10),
cati int)
insert into t select 1 ,'是非功过',1
insert into t select 2 ,'有在世界',2
insert into t select 3 ,'地区性要',3
insert into t select 4 ,'国营农场',1
insert into t select 5 ,'不堪重负',3
insert into t select 6 ,'这一点上',2
insert into t select 7 ,'要不是地',3
insert into t select 8 ,'中草药在',1
insert into t select 9 ,'是非国营',2
insert into t select 10,'为不堪重',1
insert into t select 11,'工期地区',3
--执行查询
select
a.*
from
t a
where
a.id in(select top 2 id from t where cati = a.cati order by id desc)
order by
a.cati,a.id desc
--输出结果
id subject cati
---------------------
10 为不堪重 1
8 中草药在 1
9 是非国营 2
6 这一点上 2
11 工期地区 3
7 要不是地 3Top
7 楼paoluo(一天到晚游泳的鱼)回复于 2005-04-02 16:44:04 得分 0
--建立测试环境
Create table A
(ID Int IDENTITY(1,1),
subject Nvarchar(20),
cati Int
)
GO
--插入数据
Insert A Values(N'是非功过', 1)
Insert A Values(N'有在世界', 2)
Insert A Values(N'地区性要', 3)
Insert A Values(N'国营农场', 1)
Insert A Values(N'不堪重负', 3)
Insert A Values(N'这一点上', 2)
Insert A Values(N'要不是地', 3)
Insert A Values(N'中草药在', 1)
Insert A Values(N'是非国营', 2)
Insert A Values(N'为不堪重', 1)
Insert A Values(N'工期地区', 3)
GO
--测试
select * from A T
where id in (select top 2 id from A where cati = T.cati order by id desc)
order by cati,id desc
--删除测试环境
Drop table A
--结果
/*
ID subject cati
10 为不堪重 1
8 中草药在 1
9 是非国营 2
6 这一点上 2
11 工期地区 3
7 要不是地 3
*/Top
8 楼NewQger(Q哥)回复于 2005-04-02 19:44:17 得分 0
怎么还没结?Top
9 楼Hopewell_Go(好的在后頭﹗希望更好﹗﹗)回复于 2005-04-02 22:21:08 得分 0
樓主的意思是取每個cati相等的兩條最大記錄吧
Top




