从联合表中选择记录

时间:2014-12-25 01:20:40

标签: sql select distinct

有两张桌子:

tblJumper
  JumperID
  JumperName  

tblWidthScored
  ScoreID
  fkJumperID
  fkScoredWidth

tblWidthScored.fkJumperID = tblJumper.JumperID

相关的表格

表包含以下数据:

tblJumper
  1   Tom
  2   Jerry
  3   Bugs
tblWidthScored
  1   1   5,72m
  2   2   6,13m 
  3   1   5,80m 
  4   3   6,40m
  5   2   6,30m
  6   3   6,20m

我想要获得的是每个Jumpers personla best的列表:

  Tom    5,80m
  Jerry  6,30m
  Bugs   6,40m

尝试了各种形式的SELECT DISTINCT ......但是没有以任何方式取得成功。 有人可以暗示一下吗? 谢谢!

4 个答案:

答案 0 :(得分:0)

虽然我认为这只是一个加入问题,并且可以在网上找到相应的文章,但我会发布其中一个答案......

 SELECT
  J.JumperName,
  S.Score
 FROM tblJumper as J
   INNER JOIN(
               SELECT
                 fkJumperID, 
                 Max(fkScoredWidth) as Score 
               FROM tblWidthScored 
               GROUP BY
                 fkJumperID
             ) as S on J.JumperID = S.fkJumperID

您提出的提示实际上是在您的实际问题中:

您正在努力寻找个人成就!这意味着某种聚合:Maximum

你试图明确地找到个人成就。不是"整个跳投中的最好成绩"但每个人的个人表现最为明显。这意味着您可以按人员对得分数据进行分区的某种区分或分组:Group By Clause

答案 1 :(得分:0)

您可以尝试此查询。对于此类查询,您必须将Group BY子句与子查询一起使用。

 SELECT JumperName, innertblWidthScored
 FROM tblJumper INNER JOIN(SELECT fkJumperID, 
               Max(fkScoredWidth) as innertblWidthScored
               FROM tblWidthScored 
               GROUP BY fkJumperID) WidthScored 
 on tblJumper.JumperID = WidthScored.fkJumperID

SQL FIDDLE DEMO

答案 2 :(得分:0)

您也可以从JOIN开始,然后再执行GROUP BY。如果您的示例输出确实建议了排序顺序,那么您也需要ORDER BY

SELECT
  JumperName
  , MAX(fkScoredWidth) PersonalBest
FROM tblJumper
JOIN tblWidthScored
  ON JumperID = fkJumperID
GROUP BY JumperName
ORDER BY MAX(fkScoredWidth) DESC;

SQL Fiddle

答案 3 :(得分:0)

从结果看,您似乎想要检索具有最佳分数的跳线

试试这个 -

select
  a.jumperName,
  b.bestScore
from tblJumper a, (
                    select
                      max(fkScoredWidth) as bestScore,
                      fkJumperID
                    from tblWidthScored
                    group by
                      fkJumperID
                  ) b on b.fkJumperID = a.JumperID
order by
  a.JumperID