表A分组名称 名称 数值1
AAA a1 10
AAA a2 20
AAA a3 3
BBB b1 50
BBB b2 10
BBB b3 6
---------------------------
结果分组名称 最大值名称 最大值 最小值名称 最小值 平均值
AAA a2 20 a3 3 11
BBB b1 50 b3 6 22求一sql语句
AAA a1 10
AAA a2 20
AAA a3 3
BBB b1 50
BBB b2 10
BBB b3 6
---------------------------
结果分组名称 最大值名称 最大值 最小值名称 最小值 平均值
AAA a2 20 a3 3 11
BBB b1 50 b3 6 22求一sql语句
select 分组名称,
最大值名称=(select top 1 名称 from T where 分组名称=A.分组名称 order by 数值1 desc ),
最大值=max(数值1),
最小值名称 =(select top 1 名称 from T where 分组名称=A.分组名称 order by 数值1 ),
最小值 =min(数值1),
平均值=avg(数值1)
from T as A
group by 分组名称
分组名称,
((select 名称 from (select id=row_number()over(partition by 分组名称 order by 数值1 desc),* from tb) where id=1) as 最大值名称,
max(数值1) as 最大值,
((select 名称 from (select id=row_number()over(partition by 分组名称 order by 数值1),* from tb) where id=1) as 最小值名称,
min(数值1) as 最小值,
avg(数值1) as 平均值
from
tb
group by
分组名称
最大值名称=(select top 1 名称 from T where 分组名称=A.分组名称 and 数值 =max(数值) ,
最大值=max(数值1),
最小值名称 =(select top 1 名称 from T where 分组名称=A.分组名称 and 数值 =min(数值) ,
最小值 =min(数值1),
平均值=avg(数值1)
from T as A
group by 分组名称
(
分组名称 varchar(30),
名称 varchar(20),
数值1 int
)
insert into #LL select 'AAA','a1',10
insert into #LL select 'AAA','a2',20
insert into #LL select 'AAA','a3',3
insert into #LL select 'BBB','b1',50
insert into #LL select 'BBB','b2',10
insert into #LL select 'BBB','b3',6
select 分组名称,
(select top 1 名称 from #LL where 分组名称=L.分组名称 order by 数值1 desc) '最大值名称',
max(数值1) '最大值',
(select top 1 名称 from #LL where 分组名称=L.分组名称 order by 数值1 asc) '最小值名称',
min(数值1) '最小值',
avg(数值1) '平均值'
from #LL L
group by 分组名称
分组名称 最大值名称 最大值 最小值名称 最小值 平均值
------------------------------ -------------------- ----------- -------------------- ----------- -----------
AAA a2 20 a3 3 11
BBB b1 50 b3 6 22(2 行受影响)
我的数据库是sql2000没有row_number()函数啊。。