gpt4 book ai didi

SQL GROUP BY QUERY 未返回所需的输出

转载 作者:行者123 更新时间:2023-12-02 05:06:42 24 4
gpt4 key购买 nike

这是我的表格和插入值:

create table student (


LastName varchar(40),
FirstName varchar(40),
SID number(5),
SSN number(9),
Career varchar(4),
Program varchar(10),
City varchar(40),
Started number(4),

primary key (SID),
unique(SSN)
);
create table enrolled (
StudentID number(5),
CourseID number(4),
Quarter varchar(6),
Year number(4),

primary key (StudentID, CourseID),
foreign key (StudentID) references student(SID),
foreign key (CourseID) references course(CID)
);
insert into student
values ( 'Brennigan', 'Marcus', 90421, 987654321, 'UGRD', 'COMP-GPH', 'Evanston', 2001 );
insert into student
values ( 'Patel', 'Deepa', 14662, null, 'GRD', 'COMP-SCI', 'Evanston', 2003 );
insert into student
values ( 'Snowdon', 'Jonathan', 08871, 123123123, 'GRD', 'INFO-SYS', 'Springfield', 2005 );
insert into student
values ( 'Starck', 'Jason', 19992, 789789789, 'UGRD', 'INFO-SYS', 'Springfield', 2003 );
insert into student
values ( 'Johnson', 'Peter', 32105, 123456789, 'UGRD', 'COMP-SCI', 'Chicago', 2004 );
insert into student
values ( 'Winter', 'Abigail', 11035, 111111111, 'GRD', 'PHD', 'Chicago', 2003 );
insert into student
values ( 'Patel', 'Prakash', 75234, null, 'UGRD', 'COMP-SCI', 'Chicago', 2001 );
insert into student
values ( 'Snowdon', 'Jennifer', 93321, 321321321, 'GRD', 'COMP-SCI', 'Springfield', 2004 );
insert into enrolled
values (11035, 1020, 'Fall', 2005);
insert into enrolled
values (11035, 1092, 'Fall', 2005);
insert into enrolled
values (11035, 8772, 'Spring', 2006);
insert into enrolled
values (75234, 3201, 'Winter', 2006);
insert into enrolled
values (08871, 1092, 'Fall', 2005);
insert into enrolled
values (90421, 8772, 'Spring', 2006);
insert into enrolled
values (90421, 2987, 'Spring', 2006);

我有以下查询:

SELECT e.studentid
FROM enrolled e
FULL OUTER JOIN student s ON e.studentid = s.sid
WHERE ((e.quarter = 'Fall') OR (e.quarter = 'Spring'))
GROUP BY e.studentid
HAVING count(e.studentid) = 1;

但这只会返回

8871

这应该返回

8871
90421

此查询的目标是:列出在秋季学期至少注册了一门类(class)或在 Spring 学期注册至少一门类(class)的学生,但不能同时注册这两个类(class)。您将不得不添加几行来测试您的查询。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

试一试

SELECT  a.SID
FROM student a
INNER JOIN enrolled b
ON a.SID = b.StudentID
WHERE b.quarter IN ('Fall', 'Spring')
GROUP BY a.SID
HAVING COUNT(DISTINCT b.quarter) = 1

关于SQL GROUP BY QUERY 未返回所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com