2

I am trying to query set result set which returns something like the below. I need to return only 1 row per name and need to GROUP BY but only the name that have a value of '8' under the Grade column are desired. The below is a result from another query. Because Sandra has a different value other than 8, Sandra should be omitted.

eg:- In the below I need to get one row for John only. Please advise. Thank you.

    Name      Grade
    =======   =====
    Sandra     8  
    Sandra     8
    Sandra     8
    Sandra     9
    John       8
    John       8
    John       8
    John       8


    Expected Result - 1 row

    Name     Grade
    John      8
Stackoverflow User
  • 161
  • 1
  • 4
  • 10

3 Answers3

4

Aggregate your table on the name, and then use a HAVING clause to filter out names which have a grade other than 8 (or any other values which you do not want).

SELECT name, MIN(grade) AS grade
FROM yourTable
GROUP BY name
HAVING SUM(CASE WHEN grade <> 8 THEN 1 ELSE 0 END) = 0;

Demo

Update:

If the grade column were text, and you wanted to compare against the string '8' instead of a number, then you could use this HAVING clause:

HAVING SUM(CASE WHEN grade <> '8' THEN 1 ELSE 0 END) = 0;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

If you want names that have only 8s, you can do:

select name
from t
group by name
having min(grade) = max(grade) and min(grade) = 8;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Alternately,

SELECT DISTINCT B.name, B.grade
FROM
(
    SELECT name FROM yourTable GROUP BY name HAVING COUNT(DISTINCT grade) = 1
) Z
INNER JOIN
yourTable B
ON Z.name = B.name
AND B.grade = 8;
Vash
  • 1,767
  • 2
  • 12
  • 19