0

我试图在这里将 SECTION_ID 计为 SECTIONS 并将 ENROLL_DATE 计为 STUDENTS ,我从学生列中得到正确的结果,但不是从部分列。我只想要 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
4

2 回答 2

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;
于 2013-10-30T23:51:01.053 回答
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;

您的存在标准可能没有达到您的预期,因为内部和外部之间没有相关性。您还重复s.section_id = e.section_id了 join 和 where 子句。

于 2013-10-30T23:51:22.150 回答