How to count grades that does not exist.

I have an table in which there is a column grade.
Which can have the values A+, A, B+, B, C+, C, D, E, F, I
These grades can be obtained in any subject.
For example: if in any subject grade A+ is not available it should be counted as 0.
But the following query returns only the count of the grades which are available in the table,
I want, if any of the grades does not exist it should be counted as zero.

The following command counts only the grades.

select course,subjectcode,grade,COUNT(*)
from mstmassstudents
group by course,subjectcode,grade
order by 1,2


The sample data is attached.
Grades.xlsx
searchsanjaysharmaAsked:
Who is Participating?
 
PortletPaulConnect With a Mentor freelancerCommented:
There are 3 proposals so far that produce a count of every grade for each course/subject

ID: 39252331 - using CROSS JOIN and CTEs (note you had stated you only had 1 table)
ID: 39253560 - using a UNION
ID: 39254584 - using CROSS JOIN and Grades table (adding a sorting column)

nb: any CTE of grades can be replaced by the grades table (or vice-versa)
    a sorting column may be added to a CTE of grades

There remains another way, which does not require any CTE or the Grades table, and it is has the best execution plan so far. This approach uses a CROSS APPLY:
SELECT
  r.course
, r.subjectcode
, ca1.grade
, ca1.gradecount
FROM (
      SELECT  -- this subquery produces a column of counts for each grade
              -- if new grades are introduced then new sum(...) rows would be needed for each new grade
        course
      , subjectcode
      , sum(CASE WHEN grade = 'A+' THEN 1 ELSE 0 END) AS [A+]
      , sum(CASE WHEN grade = 'A'  THEN 1 ELSE 0 END) AS A
      , sum(CASE WHEN grade = 'B+' THEN 1 ELSE 0 END) AS [B+]
      , sum(CASE WHEN grade = 'B'  THEN 1 ELSE 0 END) AS B
      , sum(CASE WHEN grade = 'C+' THEN 1 ELSE 0 END) AS [C+]
      , sum(CASE WHEN grade = 'C'  THEN 1 ELSE 0 END) AS C
      , sum(CASE WHEN grade = 'D'  THEN 1 ELSE 0 END) AS D
      , sum(CASE WHEN grade = 'E'  THEN 1 ELSE 0 END) AS E
      , sum(CASE WHEN grade = 'F'  THEN 1 ELSE 0 END) AS F
      , sum(CASE WHEN grade = 'I'  THEN 1 ELSE 0 END) AS I
      FROM mstmassstudents
      GROUP BY
        course
      , subjectcode
      ) AS r
CROSS APPLY (   -- the cross apply "unpivots" the data supplied from the above subquery
                -- from one column per Grade, 
                -- to one column of grades and one column of counts
  VALUES
          (1 ,'A+',r.[A+]) -- adding a sorting column is simple here
         ,(2 ,'A' ,r.[A])  -- and if further grades are to be included
         ,(3 ,'B+',r.[B+]) -- they would be added here
         ,(4 ,'B' ,r.[B])  -- making necessary change for sorting
         ,(5 ,'C+',r.[C+])
         ,(6 ,'C' ,r.[C])
         ,(7 ,'D' ,r.[D])
         ,(8 ,'E' ,r.[E])
         ,(9 ,'F' ,r.[F])
         ,(10,'I' ,r.[I])
      ) AS ca1 (gradesort, grade, gradecount)
ORDER BY
  r.course
, r.subjectcode
, ca1.gradesort
;

Open in new window

all of these 4 proposals are available for use and comparison at: http://sqlfiddle.com/#!3/ab8e1/3
0
 
Peter KipropCommented:
Hi  searchsanjaysharma,

You need to join Grade table master and return all rows from this table and count from mstmassstudents.
0
 
searchsanjaysharmaAuthor Commented:
I have mstmassstudent table only where grade field is there,
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
PortletPaulfreelancerCommented:
;with cte as (
                      select 'A+' as grade union all
                      select 'A' as grade union all
                      select 'B+' as grade union all
                      select 'B' as grade union all
                      select 'C+' as grade union all
                      select 'C' as grade union all
                      select 'D' as grade union all
                      select 'E' as grade union all
                      select 'F' as grade union all
                      select 'I' as grade
       )
select
  cte.grade
, count(m.grade)
from cte
left join mstmassstudents as m on cte.grade = m.grade
group by
   cte.grade

Open in new window

0
 
searchsanjaysharmaAuthor Commented:
I have created grade table where all grades are written but thsi query doesnt returning the desired result.

      SELECT A.COURSE,A.SUBJECTCODE,a.Grade,COUNT(*)
      FROM  mstmassstudents A  right outer join  grades b
        ON  A.grade=B.GRADE
       GROUP BY A.COURSE,A.SUBJECTCODE,a.Grade
      order by 1,2
0
 
PortletPaulfreelancerCommented:
SELECT
         A.COURSE
        , A.SUBJECTCODE
        , a.Grade
        , COUNT(*)
FROM  grades B
LEFT JOIN mstmassstudents A ON B.grade = A.GRADE
GROUP BY
         A.COURSE
        , A.SUBJECTCODE
        , a.Grade
ORDER BY
         A.COURSE
        , A.SUBJECTCODE
0
 
PortletPaulfreelancerCommented:
use the grades table as the FROM, this will ensure every grade is included when you left join to the details
0
 
searchsanjaysharmaAuthor Commented:
giving the same output
0
 
searchsanjaysharmaAuthor Commented:
with cte as (
                      select 'A+' as grade union all
                      select 'A' as grade union all
                      select 'B+' as grade union all
                      select 'B' as grade union all
                      select 'C+' as grade union all
                      select 'C' as grade union all
                      select 'D' as grade union all
                      select 'E' as grade union all
                      select 'F' as grade union all
                      select 'I' as grade
       )
select course,subjectcode,
  cte.grade
, count(m.grade)
from cte
left join mstmassstudents as m on cte.grade = m.grade
group by
   course,subjectcode,cte.grade


This is still missing the grades whih are not thre.
0
 
PortletPaulfreelancerCommented:
try this please:
;with cteG as (
                      select 'A+' as grade union all
                      select 'A' as grade union all
                      select 'B+' as grade union all
                      select 'B' as grade union all
                      select 'C+' as grade union all
                      select 'C' as grade union all
                      select 'D' as grade union all
                      select 'E' as grade union all
                      select 'F' as grade union all
                      select 'I' as grade
         ),
cteS as (
          select distinct course,subjectcode from mstmassstudents
        ),
cte as  (
          select course,subjectcode, grade
          from cteS
          cross join cteG
        )
select
  cte.course
, cte.subjectcode
, cte.grade
, count(m.grade)
from cte
left join mstmassstudents as m on cte.course = m.course
                              and cte.subjectcode = m.subjectcode
                              and cte.grade = m.grade
group by
  cte.course
, cte.subjectcode
, cte.grade
order by
  cte.course
, cte.subjectcode
, cte.grade

Open in new window

{+ edit see this at: http://sqlfiddle.com/#!3/e8803/5 }
0
 
Peter KipropCommented:
Try

 SELECT A.COURSE,A.SUBJECTCODE,a.Grade,COUNT(*)
      FROM  mstmassstudents A  right outer join  grades b
        ON  A.grade=B.GRADE
       GROUP BY A.COURSE,A.SUBJECTCODE,a.Grade
      order by 1,2
0
 
PortletPaulfreelancerCommented:
a right join will not make any difference, it is the use of [course] and [subject] code in the group by which is suppressing the outer join effect on grades.

select ...
from mstmassstudents as M
right join grades as G on M.grade = G.grade

is the equivalent of:

select ...
from grades as G
left join mstmassstudents as M on G.grade = M.grade

which has already failed.
0
 
PortletPaulfreelancerCommented:
COURSE SUBJECTCODE  A+   A    B+    B     C+    C    D    E    F    I
B.Com    CMP-126    0    0    25    30    25    2    7    0    3    1
B.Com    CMT-121    2    13   16    17    15    12   7    4    6    1
B.Com    CMT-122    5    6    3     7     13    6    6    1    1    0

Open in new window

whilst this is quite different to the original request, perhaps it would be useful
select
  course
, subjectcode
, sum(case when grade = 'A+' then 1 else 0 end) as [A+]
, sum(case when grade = 'A'  then 1 else 0 end) as A
, sum(case when grade = 'B+' then 1 else 0 end) as [B+]
, sum(case when grade = 'B'  then 1 else 0 end) as B
, sum(case when grade = 'C+' then 1 else 0 end) as [C+]
, sum(case when grade = 'C'  then 1 else 0 end) as C
, sum(case when grade = 'D'  then 1 else 0 end) as D
, sum(case when grade = 'E'  then 1 else 0 end) as E
, sum(case when grade = 'F'  then 1 else 0 end) as F
, sum(case when grade = 'I'  then 1 else 0 end) as I
from mstmassstudents
group by
  course
, subjectcode

Open in new window

both this and the cross join based solution - which does produce the full list of grades for every course/subject - are available to try at:
http://sqlfiddle.com/#!3/e8803/14
0
 
awking00Commented:
Given your sample data just for subjectcode CMP-126, what are your expected results?
0
 
DOSLoverCommented:
Hi SearchSanjaySharma,
Please try this:
select a.course,a.subject,a.grade, count(*) as GradeCount
  from mstmassstudents  a
  JOIN Grades b ON b.grade = a.grade
 Group by a.course,a.subject,a.grade 
UNION 
select distinct b.course, b.subject, a.grade, 0 as gradecount 
 from Grades a, mstmassstudents  b
where (select count(*) from mstmassstudents c where c.course=b.course and c.subject=b.subject and c.grade=a.grade) = 0
order by 1,2,3

Open in new window

0
 
Brendt HessSenior DBACommented:
The biggest issue is that you are grouping by more than just the grade.  To easily handle this, you need a list of all combinations of Course, SubjectCode, and Grade.  This code will provide the list needed, and join the actual grades with it:
;WITH BaseColumns AS (
	SELECT DISTINCT 
		course,
		subjectcode,
		grade,
		gradeorder  -- need this for correct sorting of grades - if you care - with A+ = 10, A=20, B+=30 etc
				-- number by 10s in case they want to add A- or some other variant in the future.
				-- If this does not exist, A sorts above A+
	FROM (
		SELECT DISTINCT 
			course,
			subjectcode
		FROM mstmassstudents
		) AS ms
	CROSS JOIN grades g
	)		-- This outputs all combinations of course, subjectcode, and grade in one list. 
SELECT 
	BaseColumns.course,
	BaseColumns.subjectCode,
	BaseColumns.grade,
	ISNULL(ActualGrades.GradeCount, 0) AS GradeCount
FROM BaseColumns
LEFT JOIN (
	SELECT 
		course,
		subjectCode,
		grade,
		COUNT(*) AS GradeCount
	FROM mstmassstudents
	GROUP BY
		course,
		subjectcode,
		grade
	) AS ActualGrades
	ON BaseColumns.course = ActualGrades.course
	AND  BaseColumns.subjectcode = ActualGrades.subjectcode
	AND  BaseColumns.grade = ActualGrades.grade
ORDER BY BaseColumns.course,
	BaseColumns.subjectCode,
	BaseColumns.gradeorder

Open in new window

0
 
PortletPaulfreelancerCommented:
Hi, have you tried any of these as yet?
0
 
searchsanjaysharmaAuthor Commented:
tx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.