sqlserver怎么根据双列来查询
sqlserver如何根据双列来查询
id name class age
1 张三 一班 5
2 李四 二班 6
3 小王 四班 10
4 赵六 二班 9
查询过后
id name class 合计 最小age 最大age
1 张三 一班 1 5 5
2 李四 二班 2 6 9
3 小王 四班 1 0 10
就是根据class列求合计值,根据age列求出合计后的最小age和最大age,像这样的查询语句怎么写,谢谢!
------解决思路----------------------
select b.*,class,count(*) cou,max(age) maxage,min(age) minage from T_student a cross apply
(select top 1 id,name from T_student T where t.class=a.class order by id) b
group by a.class,b.id,b.name
order by b.id
------解决思路----------------------
一般不会需要再加id和name的,那样没有意义吧?
------解决思路----------------------
------解决思路----------------------
with test_view as
(select class class,COUNT(1) count,MIN(age) min,MAX(age) max from test group by class)
select t.id,t.name,tv.class,tv.count,tv.min,tv.max from test t left join test_view tv on t.class = tv.class order by t.id;
查询结果:
id name class count min max
1 张三 一班 1 5 5
2 李四 二班 2 6 9
3 小王 四班 1 10 10
4 赵六 二班 2 6 9
------解决思路----------------------
select class,COUNT(class),MAX(age),MIN(age),max(name) from test group by class order by MAX(age) asc
id name class age
1 张三 一班 5
2 李四 二班 6
3 小王 四班 10
4 赵六 二班 9
查询过后
id name class 合计 最小age 最大age
1 张三 一班 1 5 5
2 李四 二班 2 6 9
3 小王 四班 1 0 10
就是根据class列求合计值,根据age列求出合计后的最小age和最大age,像这样的查询语句怎么写,谢谢!
------解决思路----------------------
select b.*,class,count(*) cou,max(age) maxage,min(age) minage from T_student a cross apply
(select top 1 id,name from T_student T where t.class=a.class order by id) b
group by a.class,b.id,b.name
order by b.id
------解决思路----------------------
select class,COUNT(*) as 合计,MIN(age) as 最小age,MAX(age) as 最大age from T_student group by class
一般不会需要再加id和name的,那样没有意义吧?
------解决思路----------------------
select class,count(1) ,min(age),max(age) from t group by class
------解决思路----------------------
with test_view as
(select class class,COUNT(1) count,MIN(age) min,MAX(age) max from test group by class)
select t.id,t.name,tv.class,tv.count,tv.min,tv.max from test t left join test_view tv on t.class = tv.class order by t.id;
查询结果:
id name class count min max
1 张三 一班 1 5 5
2 李四 二班 2 6 9
3 小王 四班 1 10 10
4 赵六 二班 2 6 9
------解决思路----------------------
select class,COUNT(class),MAX(age),MIN(age),max(name) from test group by class order by MAX(age) asc