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

分类选择完整记录的难题(group by救教)
现有一个表tablei
id     name     class
1       aaa       1
2       bbb       1
3       ccc       2
4       ddd       2
5       eee       3
6       fff       3

现在想从每一类class里选择出一条完整的记录(取出每一类的哪条都可以,无限制),使用select   *   from   tablei   group   by   class   肯定是不行的,如果记录很多,我想求教一个效率高的语句或存储过程,哪位高手可以给出完整样例,在下不胜感激

------解决方案--------------------
select * from tablei where exists(select 1 from tablei t where t.class=class and t.id> id)
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(id int,name varchar(10),class int)
insert into tb(id,name,class) values(1, 'aaa ', 1)
insert into tb(id,name,class) values(2, 'bbb ', 1)
insert into tb(id,name,class) values(3, 'ccc ', 2)
insert into tb(id,name,class) values(4, 'ddd ', 2)
insert into tb(id,name,class) values(5, 'eee ', 3)
insert into tb(id,name,class) values(6, 'fff ', 3)

select a.* from tb a,
(select class , min(id) id from tb group by class) b
where a.class = b.class and a.id = b.id

drop table tb

/*
id name class
----------- ---------- -----------
1 aaa 1
3 ccc 2
5 eee 3

(所影响的行数为 3 行)

*/
------解决方案--------------------
tonvy(tonvy) ( ) 信誉:100 Blog 加为好友 2007-05-11 15:36:50 得分: 0


如果记录有100多万条,哪个效率高?我没看出来?我感觉建立临时表(3楼那个)应该最慢吧?因为需要把100多万条记录都写进去


------
3楼那个建立的是测试表。。。。

sql语句其实就是他写的这些:
select a.* from tb a,
(select class , min(id) id from tb group by class) b
where a.class = b.class and a.id = b.id