SQL Server 按某一字段分组取最大(小)值所在行的数据

 1 -- 创建表并插入数据:
 2 create table tb
 3 (
 4   name varchar ( 10 ),
 5   val int ,
 6   memo varchar ( 20 )
 7 )
 8 insert into tb values
 9 ( ' a ' ,    2 ,   ' a2(a的第二个值) ' ),
10 ( ' a ' ,    1 ,   ' a1--a的第一个值 ' ),
11 ( ' a ' ,    3 ,   ' a3:a的第三个值 ' ),
12 ( ' b ' ,    1 ,   ' b1--b的第一个值 ' ),
13 ( ' b ' ,    3 ,   ' b3:b的第三个值 ' ),
14 ( ' b ' ,    2 ,   ' b2b2b2b2 ' ),
15 ( ' b ' ,    4 ,   ' b4b4 ' ),
16 ( ' b ' ,    5 ,   ' b5b5b5b5b5 ' )
 1 -- 一、按name分组 取 val最大 的值所在行的数据。
 2 -- 方法1:
 3 select a. * from tb a where val = ( select max (val) from tb where name = a.name) order by a.name
 4 -- 方法2:
 5 select a. * from tb a where not exists ( select 1 from tb where name = a.name and val > a.val)
 6 -- 方法3:
 7 select a. * from tb a,( select name, max (val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name
 8 -- 方法4:
 9 select a. * from tb a inner join ( select name , max (val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name
10 -- 方法5
11 select a. * from tb a where 1 > ( select count ( * ) from tb where name = a.name and val > a.val ) order by a.name
 1 -- 二、按name分组 取 val最小的值所在行的数据。
 2 -- 方法1:
 3 select a. * from tb a where val = ( select min (val) from tb where name = a.name) order by a.name
 4 -- 方法2:
 5 select a. * from tb a where not exists ( select 1 from tb where name = a.name and val < a.val)
 6 -- 方法3:
 7 select a. * from tb a,( select name, min (val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name
 8 -- 方法4:
 9 select a. * from tb a inner join ( select name , min (val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name
10 -- 方法5
11 select a. * from tb a where 1 > ( select count ( * ) from tb where name = a.name and val < a.val) order by a.name
1 -- 三、用开空函数row_number() over()
2 SELECT  * FROM (SELECT*,ROW_NUMBER() OVER( PARTITION BY name ORDER BY val DESC ) rid FROM  tb) AS t WHERE rid = 1

 

posted @ 2021-07-17 09:32  每天进步多一点  阅读(4427)  评论(0编辑  收藏  举报