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

一道简单的SQL,求高手

accpfriend 发布于 2007-01-30 16:28, 1755 次点击
if object_id('S') is not null
drop table S
go
create table S(S# nvarchar(50),SN nvarchar(100),SD nvarchar(100),SA int)
insert S select 'V001',N'小明',N'第二班',25
union all select 'V002',N'小日',N'第三班',28
union all select 'V003',N'小月',N'第一班',26
union all select 'V004',N'小萌',N'第四班',21
union all select 'V005',N'小a',N'第a班',21
go
if object_id('C') is not null
drop table C
go
create table C(C# nvarchar(50),CN nvarchar(100))
insert C select 'C001',N'英语课'
union all select 'C002',N'数学课'
union all select 'C003',N'税收基础'
union all select 'C004',N'化学课'
go
if object_id('SC') is not null
drop table SC
go
create table SC(S# nvarchar(50),C# nvarchar(50),G int)
insert SC select 'V001','C002',95
union all select 'V002','C004',45
union all select 'V001','C003',84
union all select 'V003','C002',65
union all select 'V003','C001',75
union all select 'V004','C001',55
union all select 'V004','C002',55
union all select 'V004','C003',55
union all select 'V004','C004',55
go
select * from S
select * from C
select * from SC

--查询选修全部课程的学员姓名和所属单位

\我也想了很久,但就是不知道如何下手,高手能把你做这道的是如何想,简单给我说一说,主要是做题的思路,
18 回复
#2
棉花糖ONE2007-01-30 16:34
双重not exists,论坛有一个类似的,你去找找
#3
accpfriend2007-01-30 16:36
OK
#4
棉花糖ONE2007-01-30 16:36
#5
accpfriend2007-01-30 16:41
select * from S where not exists
(
select * from SC where NOT EXISTS
(
select * from C where S#=S.S# AND C#=SC.C#
)
)
不对呀,我照样做,结果不对,而且这种方法有点晕
不太明白
给我正确答案
#6
棉花糖ONE2007-01-30 17:09
select SN,SD from S where exists
(
select count(1),S# from C,SC where C.C#=SC.C# and S.S#=S# group by S# having count(1)=(select count(1) from C)
)
双重not exists我也没写出来
#7
Kendy1234562007-01-30 17:15

我的方法是

Select N.* from S N join
(select a.S#,cnt=count(*) from S a join sc b
on a.S#=b.S#
group by a.S#
having count(*) = (select count(*) from C )
) M

on N.S#=M.S#

#8
棉花糖ONE2007-01-30 17:15
select SN,SD from S
where not exists
( select * from C where not exists (select 1 from SC where C.C#=C# and SC.S#=S.S# ) )
#9
棉花糖ONE2007-01-30 17:17
原来双重的not exists这种方法是要把含有两个关联字段的放在最内层
#10
Kendy1234562007-01-30 17:41

还是不太明白...

最精练的果然最难懂的

#11
棉花糖ONE2007-01-30 17:50
select * from S where exists( select 1 from C where not exists (select 1 from SC where C.C#=C# and SC.S#=S.S# ))
这句得到的结果是没有选择全部课程的学生
#12
daring2007-04-10 14:05
select * from s where s#=(select s# from sc group by s# having count(*)=(select count(*) from c))
#13
daidaidai2007-04-10 16:59

还是比较习惯最后一句.

#14
xiix2007-04-20 09:25
我也写了一个 好象也没出现错误 大家多多指教
select SN,SD FROM S
WHERE S.S#
IN(
SELECT SC.S# FROM SC
GROUP BY SC.S#
HAVING COUNT(*) =(SELECT COUNT(C#) FROM C)
)
#15
lbaichun2007-04-24 10:12
谢谢大家了!我也正需要这个呢!
#16
lbaichun2007-04-24 10:13
回复:(lbaichun)谢谢大家了!我也正需要这个呢!
大家是不是可以再加几个要求,多举几个例子呢!谢谢了!
#17
zsolong2007-05-16 15:41
看看这句:完全正确,符合要求。
SELECT S#,SD FROM S WHERE NOT EXISTS
(SELECT C# FROM C WHERE NOT EXISTS
(SELECT C# FROM SC WHERE S.S#=SC.S# AND C.C#=SC.C#)
)
#18
觉雨2007-05-17 09:19
哇~~
#19
YINGQUNLU2007-05-28 08:19
太好了,我也在学
1