我正在尝试将SECTION_ID作为SECTION,并将ENROLL_DATE作为学生计算在这里,我从学生专栏获得正确的结果,但不是从专栏专栏获得。我只需要来自SECTION表的SECTION_ID而不是来自ENROLLMENT表,所以我做了减去设置操作。为什么它给我两张桌子的结果?我怎么才能从SECTION表中获得结果?
SELECT s.LOCATION,COUNT(s.SECTION_ID) AS SECTIONS, COUNT(e.ENROLL_DATE) AS STUDENTS
FROM SECTION s
JOIN ENROLLMENT e
ON s.SECTION_ID = e.SECTION_ID
WHERE EXISTS (
SELECT SECTION_ID
FROM SECTION
MINUS
SELECT SECTION_ID
FROM ENROLLMENT
)
AND s.SECTION_ID = e.SECTION_ID
GROUP BY s.LOCATION
ORDER BY s.LOCATION;
我收到了这个结果
LOCATION SECTIONS STUDENTS
---------- ---------- ----------
H310 1 1
L206 8 8
L210 29 29
L211 10 10
L214 36 36
etc
我想要的结果
LOCATION SECTIONS STUDENTS
---------- ---------- ----------
H310 1 1
L206 1 8
L210 10 29
L211 3 10
L214 15 36
etc
答案 0 :(得分:1)
我最初的想法是你需要distinct关键字......
像这样:
SELECT s.LOCATION,
COUNT(DISTINCT s.SECTION_ID) AS SECTIONS,
COUNT(e.ENROLL_DATE) AS STUDENTS
FROM SECTION s
JOIN ENROLLMENT e
ON s.SECTION_ID = e.SECTION_ID
WHERE EXISTS (
SELECT SECTION_ID
FROM SECTION
MINUS
SELECT SECTION_ID
FROM ENROLLMENT
)
AND s.SECTION_ID = e.SECTION_ID
GROUP BY s.LOCATION
ORDER BY s.LOCATION;
答案 1 :(得分:1)
如果没有产生这些结果的示例数据,很难说,但我认为您可能希望计数不同:
Select
s.location,
count(distinct s.section_id) as sections,
count(e.enroll_date) as students
from
section s
inner join
enrollment e
on s.section_id = e.section_id
group by
s.location
order by
s.location;
您存在的标准可能没有达到您的预期,因为内部和外部之间没有相关性。您还在join和where子句中重复了s.section_id = e.section_id
。