0

我有以下表格:

学生(Sid,Sname) 主键:{sid}
课程(cid,cname,duration,fee) 主键:{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)

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

4

2 回答 2

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;

于 2013-09-30T19:18:42.850 回答
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
;
于 2013-09-30T19:36:29.117 回答