我正在构建一个查询,以显示运动员的姓名,基于他们参加过多个项目。
为此,我必须使用两个表,如下所示:
CREATE TABLE ATHLETE(
ATHLETEID CHAR(4),
ATHLETEFIRSTNAME VARCHAR2(20),
ATHLETELASTNAME VARCHAR2(20),
ATHLETEDOB DATE,
REPCOUNTRY VARCHAR2(12),
COACHID CHAR(4),
CONSTRAINT ATHLETE_PK PRIMARY KEY(ATHLETEID),
CONSTRAINT ATHLETE_FK1 FOREIGN KEY(COACHID) REFERENCES COACH(COACHID));
CREATE TABLE RESULTS(
EVENTID CHAR(4),
ATHLETEID CHAR(4),
RANK NUMBER(1),
CONSTRAINT RESULTS_PK PRIMARY KEY(EVENTID,ATHLETEID),
CONSTRAINT RESULTS_FK1 FOREIGN KEY(EVENTID) REFERENCES EVENTSCHEDULE(EVENTID),
CONSTRAINT RESULTS_FK2 FOREIGN KEY(ATHLETEID) REFERENCES ATHLETE(ATHLETEID));
使用下面的查询,我能够显示参加过多个项目的运动员,我正在努力的是显示运动员的姓名,因为它在不同的表中。我很确定我应该使用子查询,但是我不确定如何构建它。
SELECT A.ATHLETEID FROM RESULTS A GROUP BY A.ATHLETEID HAVING COUNT(*) > 1;
提前谢谢!
最佳答案
撇开SQL不谈,您需要重新连接到运动员,然后按所有非聚合列分组,如下所示(注意,我已将别名切换为与表名对齐):
SELECT a.ATHLETEID, a.ATHLETEFIRSTNAME,
a.ATHLETELASTNAME, COUNT(r.EVENTID) as NumEvents
FROM RESULTS r
INNER JOIN ATHLETE a
ON r.ATHLETEID = a.ATHLETEID
GROUP BY a.ATHLETEID, a.ATHLETEFIRSTNAME, a.ATHLETELASTNAME
HAVING COUNT(r.EVENTID) > 1;