我正在尝试编写一个查询,该查询将显示每个孔的最小值(最低分数),从而消除任何重复项。换句话说,如果最小分数在hole_num 1上为3并且有两个或更多分数为3,则不应返回与hole_num 1对应的行。但是,如果hole_num 1上只有一个值为3且它是最小值,则应返回该行。以下是我能够提出的......不幸的是我无法弄清楚如何删除重复项。
样本表:
player_id hole_num score
------------- ------------ -----
1 1 4
1 2 5
2 1 3
2 2 5
我的查询获得每个hole_num的最低分数(但如果多次出现,则不会删除该行):
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
产生以下输出:
player_id hole_num score
---------- --------- -----
1 2 5
2 1 3
2 2 5
我正在尝试编写一个只显示上面第二行(得分= 3)的查询,因为在hole_num 2上的5(尽管它是最小值)是重复。任何帮助将不胜感激。
答案 0 :(得分:1)
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)
您可能正在寻找:http://www.w3schools.com/sql/sql_distinct.asp
执行SELECT DISTINCT ...应该为所有完全重复的内容返回一行。