Mysql selects a minimum that is not a duplicate

I am trying to write a query that displays the minimum value (lowest score) for each hole, excluding any duplicates. In other words, if the minimum score is 3 on hole_num 1 and there are two or more points with 3, none of the lines corresponding to hole 1 should be returned. However, if on hole_num 1 there is only one value 3, and this is the minimum value, the string should be returned. Here is what I was able to come up with ... unfortunately, I cannot figure out how to remove duplicates.

Example table:

player_id     hole_num     score
------------- ------------ ----- 
1             1            4
1             2            5
2             1            3
2             2            5

my query, which gets a minimum score for each hole_num (but does not exclude a string if it occurs more than once):

select. r.player_id, r.hole_num, r.score
  from scorecard_test r
  join (select hole_num, 
               min(score) best
          from scorecard_test 
      group by hole_num) v on r.hole_num = v.hole_num
                          and r.score = v.best

outputs the following result:

player_id  hole_num  score 
---------- --------- ----- 
1          2         5 
2          1         3
2          2         5

, ( = 3), 5 hole_num 2 ( ) . .

+3
2

MySQL GROUP BY HAVING COUNT (*) = 1:

SELECT r.player_id, r.hole_num, r.score
FROM scorecard_test r
JOIN
(
    SELECT hole_num, MIN(score) best
    FROM scorecard_test
    GROUP BY hole_num
) v
ON r.hole_num = v.hole_num AND r.score = v.best
GROUP BY hole_num, score
HAVING COUNT(*) = 1

, , :

SELECT r1.player_id, r1.hole_num, r1.score
FROM scorecard_test r1
JOIN
(
    SELECT hole_num, MIN(score) best
    FROM scorecard_test
    GROUP BY hole_num
) v
ON r1.hole_num = v.hole_num AND r1.score = v.best
LEFT JOIN scorecard_test r2
ON r1.hole_num = r2.hole_num AND r1.player_id != r2.player_id AND r1.score = r2.score
WHERE r2.player_id IS NULL

:

player_id  hole_num  score 
---------- --------- ----- 
2          1         3
+1
0

Source: https://habr.com/ru/post/1763672/


All Articles