建站技术

当前位置:

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

浏览量:

对于表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:不知道有没有不用子查询的。


[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【27535611@qq.com】,我们在确认后,会立即删除,保证您的版权。