表一:学生
学号  姓名
0001  张三
0002  李四
0003  王务表二:住宿
学号  房间     入住年份
0001  c8-118   2000
0001  c8-119   2001
0001  c9-119   2002
0002  c8-118   2000我想写一个sql查询,查出当前各个学生住宿的房间,
学号  房间
0001  c9-119
0002  c8-118
0003  null
即最近的入住房间作为当前的住宿,如果没有住宿纪录则null请问该怎么写啊?

解决方案 »

  1.   

    adoquery1.sql.clear;
    adoquery1.sql.add('select 学号 from 学生');
    adoqueyr1.open;
    if adoquery1.recordcount > 0 then 
      begin
        with adoquery1 do 
          begin
             first;
             while not eof then
                begin
                   adoquery2.sql.clear;
                   adoquery2.sql.add('select 房间 from 住宿 where 学号=:a');
                   adoquery2.Parameters.ParamByName('a').value:=adoquery1.fields[0]
                     .value;
                   adoquery2.open;                 
                   next;
                end;
          end;
      end;
      

  2.   

    谢谢"cxreal(夜晚的猪)  "可是我希望用sql语言直接解决这个问题
      

  3.   

    select c.学号, d.房间
    from 学生 c, 
    (select a.*
    from 住宿 a, 
         (select 学号, max(入住年份) from 住宿) b
    where a.学号 = b.学号 and a.入住年份 = b.入住年份) d
    where c.学号 = d.学号(+)
      

  4.   

    另外需要说明的是:你的数据库结构有些问题
    最好的办法应当在学生记录中就把当前所住房间记录下来
    然后每次改变房间的时候,将变更记录到住宿表中
    这样在学生记录中存的是学生最新的房间,房间记录中存的是该学生住过的所有房间where c.学号 = d.学号(+)
    这句在不同的数据库中写法可能有些不一样,我写的是oracle中的
    ms sql server中要这样写
    where c.学号 =* d.学号其他的数据库自己看帮助吧
      

  5.   


    select c.学号
          ,d.房间
    from 学生 c
             ,(select a.* from 住宿 a
                                   ,(select 学号, max(入住年份) from 住宿) b
                                       where a.学号 = b.学号 
                                       and a.入住年份 = b.入住年份) d
    where c.学号 = d.学号
      

  6.   

    修改:
    select c.学号, d.房间
    from 学生 c, 
    (select a.*
    from 住宿 a, 
         (select 学号, max(入住年份) from 住宿 group by 学号) b
    where a.学号 = b.学号 and a.入住年份 = b.入住年份) d
    where c.学号 = d.学号(+)
      

  7.   

    select a.学号,a.房间 from  表二 a,
    (select 学号,max(入住年份) 入住年份 from 表二 group by 学号) b
    where a.学号=b.学号 and a.入住年份=b.入住年份
    union
    select 学号,'null' as 房间 from 表一 where 学号 not in (select 学号 from 表二)
      

  8.   

    select a.学号,b.房间 from a left out join b on a.学号=b.学号
      

  9.   

    select a.学号,b.房间 from a left outer join b on a.学号=b.学号
      

  10.   

    select  table1.学号,table2.房间  from table1,table2 where table1.学号=table2.学号