1、有如下数据,要求查询每个班最低分和最高分,并将最高分与最低分显示为同一列
ID Student CourseName Score
1 张三 English 80
2 张三 Math 70
3 张三 Chinese 50
4 李四 English 90
5 李四 Chinese 70
6 王五 Math 60
7 王五 English 70
8 赵六 Chinese 80
9 赵六 Math 60
10 赵六 English 90
这是我的解决方案,如有更好的,欢迎指点:
select Student,CourseName,Score
from(
select Student,CourseName,Score,
rnDesc=ROW_NUMBER() over(partition by CourseName order by Score desc),–按照分数降序给个编号(如果是按照学生的话将over()中的CourseName改为
–Student 即可)
rnAsc=ROW_NUMBER() over(partition by CourseName order by Score Asc)–按照分数升序给个编号
from dbo.Score
)T where T.rnAsc=1 or t.rnDesc=1–取按升序的第一个和按降序的第一个即为最低分和最高分
2、如题:
ID Numb type
10001in
20001in
30001out
50001in
60002in
70002out
80002in
90002in
100003out
110003out
120004in
要求查出的结果格式为:
numb in out
0001 3 1
0002 3 1
0003 0 2
0004 1 0
sql:
select numb,
sum(case type when ‘in’ then 1 else 0 end)as tIn,–统计type为”in”的数量,用sum而非count
sum(case type when ‘out’ then 1 else 0 end)as tOut,–统计type为”out”的数量,用sum而非count
from table1
group by numb