2013-10-30 76 views
0

我想在這裏將SECTION_ID作爲SECTIONS和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 

回答

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; 

你的存在條件很可能無法做你所期望的,因爲是在無相關性內部和外部。您還在連接和where子句中重複了s.section_id = e.section_id

+0

你得到了正確的結果...所以我基本上甚至不需要減去設置操作。我喜歡你的風格,這會幫助我做其他我需要的東西......謝謝! – Ris

+0

Yep - 'count(*)'統計結果集中的所有行,'count(列)'統計非空列的行數,'count(distinct列)'統計不同非空結果集中的值。 – Laurence

1

我最初的想法是,你想要的不同關鍵字...

像這樣:

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; 
+0

所以基本上我有重複嗯 – Ris

+0

@Dana,你多次數同一個會話。例如,如果學生1,2和3報名參加第1部分:你會有3條記錄(學生,部分| 1,1 | 2,1 | 3,1),這對你計算學生有效,但它是多次統計的同一部分。 – Michael