题目一、学生表 如下:
自动编号 学号 姓名 课程编号 课程名称 分数
1 2005001 张三 0001 数学 69
2 2005002 李四 0001 数学 89
3 2005001 张三 0001 数学 69
删除除了自动编号不同, 其他都相同的学生冗余信息
解答:delete from tablename where 自动编号 not in (select min(自动编号) from tablename group by 学号,姓名,课程编号,课程名称,分数)
题目二:请用SQL 语句实现:从TestDB 数据表中查询出所有月份的发生额都比101 科目相应月份的发生额高的科目。请注意:TestDB 中有很多科目,都有1 -12 月份的发生额。
AccID:科目代码,Occmonth :发生额月份,DebitOccur :发生额。数据库名:JcyAudit ,数据集:Select * from TestDB
select a.*
from TestDB a, (select Occmonth, max(DebitOccur) as maxdebitoccur from TestDB where AccID='101' group by Occmonth) b
where a.Occmonth=b.Occmonth and a.DebitOccur>b.maxdebitoccur
题目三:复制表( 只复制结构, 源表名:a新表名:b)
select into b from a where 1<>1(只复制结构,不复制内容)
select into b from a where 1=1(复制结构和内容)
题目四:日程安排提前五分钟提醒
select * from 日程安排 where datediff('minute', 开始时间,getdate())>5
题目五:有两个表A 和B ,均有key 和value 两个字段,如果B 的key 在A 中也有,就把B 的value 换为A 中对应的value
select B set B.value=(select A.value from A where A.key=B.key) where B.id=(select B.id from A,B where A.key=B.key)
题目六:
15.sql面试题(2)有表A,结构如下:
p_ID p_Num s_id
1 10 01
1 12 02
2 8 01
3 11 01
3 8 03
其中:p_ID为产品ID,p_Num为产品库存量,s_id为仓库ID。请用SQL语句实现将上表中的数据合并,合并后的数据为:
p_ID s1_id s2_id s3_id
1 10 12 0
2 8 0 0
3 11 0 8
其中:s1_id为仓库1的库存量,s2_id为仓库2的库存量,s3_id为仓库3的库存量。如果该产品在某仓库中无库存量,那么就是0代替。
解答:
select p_ID, sum(case when s_id='01' then p_Num else 0) as s1_id, sum(case when s_id='02' then p_Num else 0) as s2_id, sum(case when s_id='03' then p_Num else 0) as s3_id
from table
group by p_ID
题目七:查询学过“叶平”老师所教的所有课的同学的学号、姓名;
select ssid, sname from student where ssid in (select scsid from sc, s, t, c where t.name=叶平 and t.tid=c.tid and c.cid=sc.cid group by scsid having count(cid)=(select count(cid) as counts from t, c where t.tid=c.cid and t.name=叶平)
题目八:按平均成绩从高到低显示所有学生的“数据库”、“企业管理”、“英语”三门的课程成绩,按如下形式显示: 学生ID,,数据库,企业管理,英语,有效课程数,有效平均分’
SELECT stuId as 学生ID,(SELECT score FROM Scores WHERE Scores.stuId=t.stuId AND courseId='004') AS 数据库,(SELECT score FROM Scores WHERE Scores.stuId=t.stuId AND courseId='001') AS 企业管理,(SELECT score FROM Scores WHERE Scores.stuId=t.stuId AND courseId='006') AS 英语, COUNT(*) AS 有效课程数, AVG(t.score) AS 平均成绩
FROMScores AS t
GROUP BY stuId
ORDER BY avg(t.score) DESC
题目九:按各科平均成绩从低到高和及格率的百分数从高到低顺序
SELECT t.courseId AS 课程号,max(course.courseName)AS 课程名,isnull(AVG(score),0) AS 平均成绩,100 * SUM(CASE WHEN isnull(score,0)>=60 THEN 1 ELSE 0 END)/COUNT(*) AS 及格百分率
FROM Scores T,Course
where t.courseId=course.courseId
GROUP BY t.courseId
ORDER BY 100 * SUM(CASE WHEN isnull(score,0)>=60 THEN 1 ELSE 0 END)/COUNT(*) DEScores
题目十:1981年出生的学生名单(注:Student表中stuAge列的类型是datetime)
select stuName, datediff(year,stuAge, getdate()) as age
from student
where convert(nvarchar(11), datepart(year, stuAge))='1981'
题目十一:查询两门以上不及格课程的同学的学号及其平均成绩
select stuID, avg(isnull(score,0) from Scores where stuID in (select stuID from Scores where score<60 group by stuID having count(*)>2) group by stuID