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

求一个SQL语句,比较麻烦
有这样的一个表格

单位 金额 分类
a 10 1
a 8 2
b 1 1
c 1 2

我要得到每个单位分类值最大的记录,结果如下所示

单位 金额 分类
a 8 2
b 1 1
c 1 2

请问这个sql该怎么写

------解决方案--------------------
select a.* from tb where 分类 = (select max(分类) from tb where 单位=a.单位)
------解决方案--------------------
SQL code
--按记录顺序取第一条
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())

------解决方案--------------------
SQL code
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