Class 年获得重复项的主要计数(ORACLE PL/SQL)

Major count by Class Year getting duplicates(ORACLE PL/SQL)

我正在尝试获取每个 class 年的主要计数。我怎样才能每 class 年获得一个号码?

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

谢谢!

我想你想要 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;

您可以使用左连接并按

分组
  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