如何解决这个独特的SQL查询?

时间:2013-09-30 19:11:34

标签: sql oracle database

我有以下表格:

学生(Sid,Sname)主键:{sid}
课程(cid,cname,期限,费用)主键:{cid}
注册(sid,cid)外键:{sid,cid}

  

查询:查找每个学生可以支付的最高费用   报名参加不同的课程。

我的尝试:

SELECT ssid, max(fee) as MAX_FEES from (Select sid as ssid, C.cid asccid, 
fee from Course C,Enrolled E where C.cid = E.cid) group by
rollup(ssid,ccid,fee)

但是,这并未适当地提供所需的输出。如何只输出每个学生支付的最高费用?

2 个答案:

答案 0 :(得分:1)

尝试

SELECT max(c.fee) from course c, student s, enrolled e where s.sid=e.sid and e.cid=c.cid group by e.sid;

答案 1 :(得分:0)

你没有说你是否还需要列出没有参加任何课程的学生,所以我会再提供一个解决方案:

CREATE TABLE student (
  sid NUMBER PRIMARY KEY,
  sname VARCHAR2(40)
);

CREATE TABLE course (
  cid NUMBER PRIMARY KEY,
  cname VARCHAR2(40),
  duration NUMBER,
  fee NUMBER
);

CREATE TABLE enrolled (
  sid NUMBER,
  cid NUMBER,
  PRIMARY KEY (sid, cid),
  FOREIGN KEY (sid) REFERENCES student (sid),
  FOREIGN KEY (cid) REFERENCES course (cid)
);

INSERT INTO student (sid, sname) VALUES (1, 'John');
INSERT INTO student (sid, sname) VALUES (2, 'Peter');
INSERT INTO student (sid, sname) VALUES (3, 'Jake');

INSERT INTO course (cid, cname, duration, fee) VALUES (1, 'Math', 1, 1000);
INSERT INTO course (cid, cname, duration, fee) VALUES (2, 'Physics', 1, 1500);

INSERT INTO enrolled (sid, cid) VALUES (1, 1); -- John taking Math
INSERT INTO enrolled (sid, cid) VALUES (1, 2); -- John taking Physics

-- Peter being lazy

INSERT INTO enrolled (sid, cid) VALUES (3, 1); -- Jake taking Math
COMMIT;

-- not taking lazy (not taking any courses) students under account
SELECT s.sid, MAX(c.fee)
  FROM student s
    JOIN enrolled e ON (e.sid = s.sid)
    JOIN course c ON (e.cid = c.cid)
GROUP BY s.sid
;

-- all students
SELECT s.sid, NVL(MAX(c.fee), 0)
  FROM student s
    LEFT JOIN enrolled e ON (e.sid = s.sid)
    LEFT JOIN course c ON (e.cid = c.cid)
GROUP BY s.sid
;