select 学号,成绩
from 选课模式 A
where (Select count(*) from 选课模式 B where A.学号 = B.学号 and 
(课号 = '001' or 课号 = '002')) = 2

解决方案 »

  1.   

    这个是我后来写的.我想知道intersect是怎样用!select 学号,成绩
    from 选课模式
    where 课号='001' and 学号 in (select 学号 from  选课模式 where 课号='002')
    go
      

  2.   

    Intersect
    返回两个输入集合的交集,可以选择保留重复项。 语法
    Intersect(«Set1», «Set2»[, ALL])注释
    此函数返回 «Set1» 和 «Set2» 的交集。根据默认设置,在相交之前先删除两个集合中的重复项。可选的 ALL 保留重复项。ALL 有几种工作方式。算法是:不重复的元素照常相交。对于 «Set1» 中的每个重复项,将其与 «Set2» 中的重复项相匹配,如果存在匹配的项,则在交集中保留匹配的重复项。示例Intersect({[1994], [1995], [1996]}, {[1995], [1996], [1997]})返回集合 {[1995], [1996]}
      

  3.   

    但是INTERSECT 怎样写呢?
    楼上二楼的tommysun() 写的SQL可否解析下,小弟我看不明白.
    select 学号,成绩
    from 选课模式 A
    where (Select count(*) from 选课模式 B where A.学号 = B.学号 and 
    (课号 = '001' or 课号 = '002')) = 2
      

  4.   

    你寫的SQL將只返回課號為001的記錄,得不到002的成績,此語句的意思為:
    從選課模式中查找記錄必須滿足條件,此學號的學生在在選課模式表中選擇了
    課號001或002的記錄有兩條
      

  5.   

    还有其他的SQL语句写法吗?请各位大侠帮小弟想想。
      

  6.   

    --建表
    create table 成绩(学号 char(6),课号 char(3),成绩 numeric(5,2))
    go
    --插入数据
    insert into 成绩
    select '967851',      '001',    98.0  union all
    select '978424',      '001',    82.5  union all
    select '984112',      '002',    100.0 union all
    select '984113',      '001',    85.0  union all
    select '984118',      '003',    87.0  union all
    select '984555',      '001',    79.9  union all
    select '985785',      '003',    81.0  union all
    select '967851',      '002',    84.0
    go
    --查询
    select a.*,课号二=b.课号,成绩二=b.成绩 from 
    (select * from 成绩 where 课号='001') a,(select * from 成绩 where 课号='002') b
    where a.学号=b.学号--结果
    /*
    学号     课号   成绩      课号二  成绩二     
    ------ ---- ------- ---- ------- 
    967851 001  98.00   002  84.00(所影响的行数为 1 行)
    */
      

  7.   

    --或者
    select * from 成绩
    where 学号 in (
    select 学号 from 成绩
    where 课号 in ('001','002')
    group by 学号
    having count(*)=2)--结果
    /*
    学号     课号   成绩      
    ------ ---- ------- 
    967851 001  98.00
    967851 002  84.00(所影响的行数为 2 行)
    */
      

  8.   

    Intersect是求集合的交集而不是数据集的交集,所以不能用在这里select 学号,成绩
    from 选课模式
    where 课号='001' and
          学号 in (select distinct 学号 from 选课模式 where 课号='002')
      

  9.   

    --或者
    select * from 成绩
    where 课号 in ('001','002') and (select count(*) from 成绩 a where 成绩.学号=a.学号)=2--结果
    /*
    学号     课号   成绩      
    ------ ---- ------- 
    967851 001  98.00
    967851 002  84.00(所影响的行数为 2 行)
    */
      

  10.   

    select a.*,b.课号,b.成绩
      from 选课模式 a inner join 选课模式 b on a.学号= b.学号
    where a.课号='001' and b.课号='002'
     go这个是小弟想的写法。
      

  11.   

    select *
      from 选课模式 a inner join 选课模式 b on a.学号= b.学号
    where a.课号='001' and b.课号='002