sqlserver 多列查询,集锦最大最小列
sqlserver 多列查询,汇总最大最小列
id name age height
1 a1 5 20
2 a2 12 50
3 a1 8 30
4 a2 15 80
5 a1 10 100
6 a3 7 70
查询过后:
name 汇总 最小 height 最大 height
a1 3 5 20 10 100
a2 2 12 50 15 80
a3 1 7 70 7 70
就是根据name列分组,根据age列求最大最小并得到最大最小列的height值,像这样的查询语句要怎么写,谢谢!
------解决思路----------------------
id name age height
1 a1 5 20
2 a2 12 50
3 a1 8 30
4 a2 15 80
5 a1 10 100
6 a3 7 70
查询过后:
name 汇总 最小 height 最大 height
a1 3 5 20 10 100
a2 2 12 50 15 80
a3 1 7 70 7 70
就是根据name列分组,根据age列求最大最小并得到最大最小列的height值,像这样的查询语句要怎么写,谢谢!
------解决思路----------------------
with tb (id,name,age,heigth) as (
select 1,'a1',5,20 union all
select 2,'a2',12,50 union all
select 3,'a1',8,30 union all
select 4,'a2',15,80 union all
select 5,'a1',10,100 union all
select 6,'a3',7,70
),
tb1 as
(
select name,COUNT(*)num,MIN(age)minage,
MAX(age)maxage from tb group by name
)
select name,num,minage,
(select heigth from tb b where name=a.name and age=a.minage)minheigth,
maxage,
(select heigth from tb c where name=a.name and age=a.maxage)maxheigth
from tb1 a
name num minage minheigth maxage maxheigth
---- ----------- ----------- ----------- ----------- -----------
a1 3 5 20 10 100
a2 2 12 50 15 80
a3 1 7 70 7 70