SQL无法理解逻辑

时间:2012-09-19 11:02:36

标签: sql hsqldb

我有一个带有以下架构的板球数据库:

Bowl(BowlID, MatchID, Striker, Non-Striker, Bowler, Runs, OverNum)
 - Stores info for every ball
Match(MatchID, Team1, Team2, Date)
 - Stores all the matches

我正在努力弄清楚比赛中倒数第二个球的百分比是否达到了一定数量。

所以首先我需要得到每场比赛的倒数第二球。哪个我无法真正解决该怎么做。 OverNum列存储球数,因此对于20场比赛,这将从'0.1'开始并上升到'19 .6'(假设他们持续了局。)

会是这样的:

SELECT MatchID, MAX(OverNum) 
FROM Bowl 
WHERE OverNum 
NOT IN (SELECT Max(OverNum) FROM Bowl)
GROUP BY MatchID

我无法确定它是否需要每场比赛的倒数第二,而不是整个碗桌中的第二高OverNum ......

3 个答案:

答案 0 :(得分:0)

要获得倒数第二球,请使用此选项:

select *
from (
   select matchid, overnum,
          row_number() over (partition by matchid order by overnum desc) as rn
   from bowl
) t
where rn = 2;

您没有提到您正在使用的DBMS。以上是ANSI标准SQL,几乎所有现代DBMS都支持。

答案 1 :(得分:0)

  

我正在努力弄清楚比赛中倒数第二个球的百分比是否达到了一定数量。

这些内容:

SELECT 
    -- Consider each case where the runs scored on the
    -- penultimate ball is what you wanted as a '1' and rest as '0'
    (SUM(CASE Runs 
        WHEN @needed THEN 1
        ELSE 0
    END) * 100) / SUM(1),
FROM 
    Bowl b1
    JOIN 
    (
        // Penultimate ball in a given match.
        SELECT bNextMax.MatchId, Max(CONVERT(REAL, bNextMax.OverNum)) 
        FROM 
            Bowl bNextMax
            JOIN (
                SELECT MatchId, MAX(CONVERT(REAL, OverNum)) OverNum
                FROM Bowl 
                GROUP BY MatchID
            ) as bMax
            ON bNextMax.MatchID = bMax.MatchID AND bNextMax.OverNum != bMax.OverNum
    ) b2
    ON b1.MatchID = b2.MatchID AND b1.OverNum = b2.OverNum

答案 2 :(得分:0)

您需要使用稍微复杂的内部查询。我当然假设您正在使用SQL Server,尽管Oracle实际上可能会让这更容易。

select * from Bowl b
where OverNum = 
(
    select top 1 OverNum from 
    (
        select top 2 OverNum 
        from Bowl 
        where Bowl.MatchID = b.MatchID 
        order by OverNum desc
    ) top2 
    order by OverNum asc
)