2012-03-13 94 views
1

我已經形成了德比以下查詢來計算所有棒球運動員的安打率...如何選擇MAX SQL

SELECT p1.nameFirst as "First", 
p1.nameLast as "Last", 
(b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) as "SLUGGING" 
FROM Batting b1 join Players p1 on b1.playerID = p1.playerID 
WHERE AB >= 400; 

它生產的所有打者誰在蝙蝠有400以上,並計算它們的猛擊的百分比。我的問題是,我只需要選擇一個最大塞流率的球員。我嘗試用SELECT MAX圍繞數學模塊,但無濟於事。我期望的輸出...

何塞·包蒂斯塔0.7426900584795321637426900

此外,有沒有什麼辦法來格式化小數到數字的設定金額是多少?任何建議表示讚賞。

回答

2

ORDER BY SLUGGING DESC LIMIT 1添加到您的查詢,你應該得到最好的結果。

編輯: 看來Derby不支持限制返回的行數。那麼最好的方法是創建一個帶有最大壓制效果的子查詢,並加入到獲得playerId來打印。

+1

謝謝你的建議。我最終找到了限制的解決方法。通過削減DESC FETCH FIRST 1ROWS ONLY; – MCR 2012-03-14 00:21:00

0

我開始懷疑我是否幫助你爲MBA寫作或做計算機科學作業。 :-)

SELECT 
    p1.nameFirst as "First", 
    p1.nameLast as "Last", 
    b.s AS "SLUGGING" 
FROM 
(
    SELECT 
     MAX(
      (b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) 
     ) AS s 
    FROM 
     Batting b1 
    WHERE 
     b1.AB >= 400 
) m1 
JOIN 
    Batting b 
     ON 
       m1.s = (b.H + (2 * b.doubles) + (3 * b.triples) + (4 * b.HR))/(b.AB * 1.0) 
JOIN 
    Players p1 
     ON 
      b1.playerID = p1.playerID 
WHERE 
    b1.AB >= 400 

OR

*不知道這是支持

SELECT 
    TOP 1 
    p1.nameFirst as "First" 
    , p1.nameLast as "Last" 
    , (b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) AS "SLUGGING" 
FROM 
    Batting b1 
JOIN 
    Players p1 on b1.playerID = p1.playerID 
WHERE 
    b1.AB >= 400 
ORDER BY 
    (b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) DESC 

OR

*我認爲,這將工作

SELECT * FROM (
SELECT 
    ROW_NUMBER() OVER(
     ORDER BY 
      (b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) DESC 
    ) as rownum 
    , p1.nameFirst as "First" 
    , p1.nameLast as "Last" 
    , (b1.H + (2 * b1.doubles) + (3 * b1.triples) + (4 * b1.HR))/(b1.AB * 1.0) AS "SLUGGING" 
FROM 
    Batting b1 
JOIN 
    Players p1 on b1.playerID = p1.playerID 
WHERE 
    b1.AB >= 400 
) AS r 
WHERE r.rownum = 1 
+0

SELECT p1.nameFirst如 「第一」, p1.nameLast爲 「最後」, m1.s AS 「段塞」 FROM ( SELECT MAX( (b1.H +(2個* b1.doubles) +(3 * b1.triples)+(4 * b1.HR))/(b1.AB * 1.0) )爲S FROM 擊球B1 )M1 加入 擊球b ON m1.s =( bH +(2 * b.doubles)+(3 * b.triples)+(4 * b.HR))/(b.AB * 1.0) 加入 玩家p1 ON b.playerID = p1.playerID WHERE b.AB> = 400; – MCR 2012-03-13 23:45:30

+0

我不得不修改你的第一個查詢(見上面),但現在它給了我「錯誤:試圖除以零」。原來這條語句SELECT MAX( (b1.H +(2 * b1.doubles)+(3 * b1.triples)+(4 * b1.HR))/(b1.AB * 1.0) )AS s正在返回空。任何想法爲什麼? – MCR 2012-03-13 23:49:15

+0

我最終找到了基於其他帖子的解決方法,但我很好奇看到這種方法。任何想法爲什麼它除以0?謝謝 – MCR 2012-03-14 00:23:29