日期:2014-05-17  浏览次数:20439 次

如何理解这段SQL:取每组前几条记录的SQL写法
有个项目需求,需要将一些重复数据分组,然后取每组前1条。在网上搜到这段代码:


--对于表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

详细见 http://blog.sina.com.cn/s/blog_412897e10100r2rq.html

如何理解这个 
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
 这条语句?
希望大家都来讨论下
sql 分组查询 sql语句 分组取第一条