主营业务:网站制作 网站优化 小程序制作 石家庄网站制作网站建设有限公司欢迎您!
石家庄闪云网络科技有限公司
客服热线15383239821
如何让自己的网站更有质量?

取每组前几条记录的SQL写法

发布时间:2011/4/15 15:55:19

对于表test2(id是主键),有:

SELECT [id], [title], [typeid], [datetime] FROM [xahh].[dbo].[test2]

id     title    typeid datetime
1    1.1       1           1
2     1.2      1           2
3     1.3      1           3
4     2.1      2           4
5     2.2      2           5
6     2.3      2           6
7     3.1      3           7
8     3.2      3           8
9     3.3       3           9

取每个typeid的最大datetime的2条:

第一种取法:

select * from test2 a where
   (select count(*) from test2 b where b.typeid = a.typeid and a.datetime< b.datetime) <=1
order by typeid, datetime desc

[解释:相同typeid的记录中比该记录datetime小的记录数不能大于1,可以保证该记录在前2条]

结果
id     title    typeid datetime
3     1.3     1          3
2     1.2     1          2
6     2.3     2          6
5     2.2     2          5
9     3.3     3          9
8     3.2    3          8

第二种取法:

select * from test2 a where a.id in
   (select top 2 b.id from test2 b where b.typeid = a.typeid order by datetime desc)
order by typeid, datetime desc

结果
id     title    typeid datetime
3     1.3     1          3
2     1.2     1          2
6     2.3     2          6
5     2.2     2          5
9     3.3     3          9
8     3.2    3          8

PS:不知道有没有不用子查询的。

相关新闻推荐

在线客服 : 服务热线:15383239821 电子邮箱: 27535611@qq.com

公司地址:石家庄市新华区九中街江西大厦4062

备案号:冀ICP备2022000585号-4