日期:2014-05-18 浏览次数:20600 次
--按记录顺序取第一条 select a.* from tb a where 分类=(select top 1 分类 from tb where where 单位=a.单位) --取最小 select * from @test a where 分类=(select min(分类) from tb where where 单位=a.单位) --取最大 select * from @test a where 分类=(select max(分类) from tb where where 单位=a.单位) --随机取 select * from @test a where 分类=(select top 1 分类 fromtb where where 单位=a.单位 order by newid())
------解决方案--------------------
create table tb(单位 varchar(10),金额 int,分类 int)
insert into tb values('a',     10,  1 )
insert into tb values('a',     8 ,  2 )
insert into tb values('b',     1 ,  1 )
insert into tb values('c',     1 ,  2 )
go
--按记录顺序取第一条
select a.* from tb a where 分类 = (select top 1 分类 from tb where 单位=a.单位)
/*
单位         金额          分类          
---------- ----------- ----------- 
a          10          1
b          1           1
c          1           2
*/
--取最小
select a.* from tb a where 分类=(select min(分类) from tb where 单位=a.单位)
/*
单位         金额          分类          
---------- ----------- ----------- 
a          10          1
b          1           1
c          1           2
*/
--取最大
select a.* from tb a where 分类=(select max(分类) from tb where 单位=a.单位)
/*
单位         金额          分类          
---------- ----------- ----------- 
c          1           2
b          1           1
a          8           2
*/
--随机取
select a.* from tb a where 分类=(select top 1 分类 from tb where 单位=a.单位 order by newid())
/*
单位         金额          分类          
---------- ----------- ----------- 
a          8           2
b          1           1
c          1           2
(所影响的行数为 3 行)
*/
drop table tb