sql 查询练习

时间:2023-03-10 06:46:46
sql 查询练习

1. 用一条SQL 语句 查询出每门课都大于80 分的学生姓名
name kecheng fenshu
张三 语文 81
张三 数学 75
李四 语文 76
李四 数学 90
王五 语文 81
王五 数学 100
王五 英语 90

答案:select * from kaoshi where name not in(select name from kaoshi where fenshu<80)

2. 学生表 如下:
自动编号 学号 姓名 课程编号 课程名称 分数
1 2005001 张三 0001 数学 69
2 2005002 李四 0001 数学 89
3 2005001 张三 0001 数学 69
删除除了自动编号不同, 其他都相同的学生冗余信息

答案:delete tablename where 自动编号 not in(select min( 自动编号) from tablename group by 学号, 姓名, 课程编号, 课程名称, 分数)

注意:min()取得是分组后最小的值

3.一个叫 team 的表,里面只有一个字段name, 一共有4 条纪录,分别是a,b,c,d, 对应四个球队,现在四个球队进行比赛,用一条sql 语句显示所有可能的比赛组合.

答案:select * from kaoshi as a inner join kaoshi as b on a.name<b.name

select a.name,b.name from team as a inner join team b on a.name < b.name

4.

怎么把这样一个表儿
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4

答案:

select distinct a.a,a.c,b.c,c.c,d.c from kaoshi as a inner join kaoshi as b on a.b<b.b
inner join kaoshi as c on b.b<c.b
inner join kaoshi as d on c.b<d.b

答案二.

select year,
(select amount from aaa m where month=1 and m.year=aaa.year) as m1,
(select amount from aaa m where month=2 and m.year=aaa.year) as m2,
(select amount from aaa m where month=3 and m.year=aaa.year) as m3,
(select amount from aaa m where month=4 and m.year=aaa.year) as m4
from aaa group by year

5.

原表:
courseid coursename score
-------------------------------------
1 java 70
2 oracle 90
3 xml 40
4 jsp 30
5 servlet 80
-------------------------------------
为了便于阅读, 查询此表后的结果显式如下( 及格分数为60):
courseid coursename score mark
---------------------------------------------------
1 java 70 pass
2 oracle 90 pass
3 xml 40 fail
4 jsp 30 fail
5 servlet 80 pass
---------------------------------------------------
写出此查询语句

答案:

select a.courseid,a.coursename,a.score,(case when a.score>=60 then 'pass' else 'fail' end)as mark from kaoshi as a

-----------------6

create table testtable1
(
id int IDENTITY,
department varchar(12)
)

select * from testtable1
insert into testtable1 values('设计')
insert into testtable1 values('市场')
insert into testtable1 values('售后')
/*
结果
id department
1 设计
2 市场
3 售后
*/
create table testtable2
(
id int IDENTITY,
dptID int,
name varchar(12)
)
insert into testtable2 values(1,'张三')
insert into testtable2 values(1,'李四')
insert into testtable2 values(2,'王五')
insert into testtable2 values(3,'彭六')
insert into testtable2 values(4,'陈七')
/*
用一条SQL语句,怎么显示如下结果
id dptID department name
1 1 设计 张三
2 1 设计 李四
3 2 市场 王五
4 3 售后 彭六
5 4 黑人 陈七
*/

答案:

select a.id,a.dptID,isnull(b.department ,'黑人')department,a.name from testtable2 as a left join testtable1 as b
on a.dptID=b.id

注意isnull()  他是null就为黑人 不为空就正常

------------------------------------7

查询A(ID,Name)表中第31至40条记录,ID作为主键可能是不是连续增长的列

答案:select top 10 * from A where ID not in(select top 30 ID from A)