2017-08-04 60 views
0

我想要獲得每個班級的主要計數。我怎樣才能得到每個班級的一個號碼?按類別劃分的重要計數年份重複數據(ORACLE PL/SQL)

SELECT DISTINCT e.pref_class_year "CLASS" 
       ,(SELECT COUNT (*) FROM degrees d 
         WHERE d.id_number = e.id_number 
          AND (d.major_code1 = '12' 
           OR d.major_code2 = '12' 
           OR d.major_code3 = '12')) "COUNT" 

FROM entity e 

WHERE e.record_type_code = 'AL' 
    AND e.pref_class_year BETWEEN '1965' AND '2017' 

ORDER BY 1; 

Output: 
------------ 
1965 0 
1965 1 
1965 2 
1966 0 
1966 1 
1966 2 
1966 3 
1966 4 
1967 0 
1967 1 
1967 2 
1968 0 
1968 1 
1968 2 
1968 3 
1969 0 
1969 1 
1969 2 

謝謝!

回答

1

我想你想一個joingroup by

SELECT e.pref_class_year as "CLASS" 
     COUNT(d.id_number) 
FROM entity e LEFT JOIN 
    degrees d 
    ON d.id_number = e.id_number AND 
     '12' IN (d.major_code1, d.major_code2, d.major_code3) 
WHERE e.record_type_code = 'AL' AND 
     e.pref_class_year BETWEEN '1965' AND '2017' 
GROUP BY e.pref_class_year 
ORDER BY 1; 
+0

真棒加入和組!感謝Gordon的幫助!像魅力一樣工作! – JD23

0

你可以使用左由

SELECT e.pref_class_year "CLASS" 
    , nvl(COUNT (*), 0) 
    from entity e 
    left join degrees d on d.id_number = e.id_number AND 
        (d.major_code1 = '12' 
         OR d.major_code2 = '12' 
         OR d.major_code3 = '12') 
    WHERE e.record_type_code = 'AL' 
    AND e.pref_class_year BETWEEN '1965' AND '2017' 
    group by e.pref_class_year 
    ORDER BY 1