注册 登录
编程论坛 SQL Server论坛

关系代数求最小成绩

lx996263830 发布于 2017-03-06 10:45, 2385 次点击
r(R)=(sNo,sName,score),sNo为主码,用关系代数求最小成绩
2 回复
#2
mywisdom882017-03-06 16:41
不知道这个公式是怎么样的。但在 SQL Server 中,求最小数,是可以的。如下:
假设:数据表结构是:stu(sNo varchar(10),sName varchar(20),nScore numeric(5,2))
-- 以下语句在 SQL2000 中测试通过
-- 如果临时表 #stu 存在,就删除临时表 #stu
if object_id('tempdb..#stu') is not null drop table #stu
-- 建立临时表 #stu ,测试数据
create table #stu(sNo varchar(10),sName varchar(20),nScore numeric(5,2))
-- 往临时表插入测试数据
insert into #stu(sNo,sName,nScore)
select 's10001','张三',85.50 union all
select 's10002','李四',85.50 union all
select 's10001','张三',75.00 union all
select 's10002','李四',95.00 union all
select 's10002','李四',65.50 union all
select 's10001','张三',55.00

-- 求每个人的最低分,如果同1个人的 sName 相同时,sNo也相同的话
select sNo,sName,min(nScore) as MinScore from #stu
group by sNo,sName

-- 求每个人的最高分,如果同1个人的 sName 相同时,sNo也相同的话
select sNo,sName,max(nScore) as MaxScore from #stu
group by sNo,sName
只有本站会员才能查看附件,请 登录


-- 如果同1个人的 sName 相同时,但sNo 不相同时,则用下面的数据测试
if object_id('tempdb..#stu1') is not null drop table #stu1
-- 建立临时表 #stu ,测试数据
create table #stu1(sNo varchar(10),sName varchar(20),nScore numeric(5,2))
-- 往临时表插入测试数据
insert into #stu1(sNo,sName,nScore)
select 's10001','张三',85.50 union all
select 's10003','李四',85.50 union all
select 's10004','张三',75.00 union all
select 's10005','李四',95.00 union all
select 's10006','李四',65.50 union all
select 's10007','张三',55.00

-- 求最小值,
select s2.sNo,s1.sName,s1.MinScore from (select sName,min(nScore) as MinScore from #stu1 group by sName)s1
left join (select * from #stu1)s2
on s1.sName=s2.sName and s1.MinScore=s2.nScore

-- 求最大值,
select s2.sNo,s1.sName,s1.MaxScore from (select sName,Max(nScore) as MaxScore from #stu1 group by sName)s1
left join (select * from #stu1)s2
on s1.sName=s2.sName and s1.MaxScore=s2.nScore
只有本站会员才能查看附件,请 登录
#3
mywisdom882017-03-06 16:46
同人不同sNo,优化后
-- 如果同1个人的 sName 相同时,但sNo 不相同时,则用下面的数据测试

if object_id('tempdb..#stu1') is not null drop table #stu1
-- 建立临时表 #stu ,测试数据
create table #stu1(sNo varchar(10),sName varchar(20),nScore numeric(5,2))
-- 往临时表插入测试数据
insert into #stu1(sNo,sName,nScore)
select 's10001','张三',85.50 union all
select 's10003','李四',85.50 union all
select 's10004','张三',75.00 union all
select 's10005','李四',95.00 union all
select 's10006','李四',65.50 union all
select 's10007','张三',55.00

-- 求最小值,
select s2.sNo,s1.sName,s1.MinScore from (select sName,min(nScore) as MinScore from #stu1 group by sName)s1
left join #stu1 s2
on s1.sName=s2.sName and s1.MinScore=s2.nScore

-- 求最大值,
select s2.sNo,s1.sName,s1.MaxScore from (select sName,Max(nScore) as MaxScore from #stu1 group by sName)s1
left join #stu1 s2
on s1.sName=s2.sName and s1.MaxScore=s2.nScore
1