感觉挺有意思的SQL题目

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

1	0001	in  
2	0001	in  
3	0001	out 
5	0001	in  
6	0002	in  
7	0002	out 
8	0002	in  
9	0002	in  
10	0003	out 
11	0003	out 
12	0004	in  

 要求查出的结果格式为:

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

posted @ 2013-09-22 16:26  程序有Bug  阅读(237)  评论(0编辑  收藏  举报