读书人

SQL语句比较麻烦

发布时间: 2012-03-03 15:33:03 作者: rapoo

求一个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          1b          1           1c          1           2*/--取最小select a.* from tb a where 分类=(select min(分类) from tb where 单位=a.单位)/*单位         金额          分类          ---------- ----------- ----------- a          10          1b          1           1c          1           2*/--取最大select a.* from tb a where 分类=(select max(分类) from tb where 单位=a.单位)/*单位         金额          分类          ---------- ----------- ----------- c          1           2b          1           1a          8           2*/--随机取select a.* from tb a where 分类=(select top 1 分类 from tb where 单位=a.单位 order by newid())/*单位         金额          分类          ---------- ----------- ----------- a          8           2b          1           1c          1           2(所影响的行数为 3 行)*/drop table tb 

读书人网 >SQL Server

热点推荐