第一题: 如下面的表table: Id Name Class Count Date 1 苹果 水果 10 2011-7-1 1 桔子 水果 20 2011-7-2 1 香蕉 水果 15 2011-7-3 2 白菜 蔬菜 12 2011-7-1 2 青菜 蔬菜 19 2011-7-2 如果想要得到下面的结果:(Id唯一,Date选最近的一次) 1 香蕉 水果 15 2011-7-3 2 青菜 蔬菜 19 2011-7-2 分析: 同一类水果或蔬菜,找出日期最新的那一条记录。采用正向思维无法解决问题,如用max找出日期最大的,但是只得到了日期,却没有得到记录。只能使用 双重否定 即为肯定 这种思路。 正确思路为:要找这么一条记录,他的日期不比 同类 中 任何一条小。sql 应为 Select * from table t1 Where Exists(Select 1 from table t2 where t1.Class=t2.Class And t1.Date<t2.Date) ---------------------------- 第二题 有三张表 学生表 Student(Sno,Sname) 课程表Course(Cno,Cname) 选课表SC(Sno,Cno) 要求找出:选修了全部课程的学生名称 分析: 这道题 也比较适用于双重否定。即找出 没有 任何一门课程没选的 学生,选课表中有学生的选课信息,课程表中有所有课程的信息,三个表关联。 思路为:找出这么一种学生,没有任一门课程没选。sql为 Select * from Student s Where not Exists( Select 1 from Course c Where not Exists( Select 1 from SC Where Sno=s.Sno And Cno=c.Cno ) ) |
|
来自: johnny_net > 《sql server》