0

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

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

我试图计算出比赛中倒数第二个球的百分比是多少。

所以首先我需要得到每场比赛的倒数第二个球。我真的不知道该怎么做。OverNum 列存储了球号,因此对于 2020 场比赛,这将从“0.1”开始到“19.6”(假设他们坚持了几局)。

会不会是这样的:

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

我无法确保它从每场比赛中获得倒数第二,而不是从整个碗桌中获得第二高的 OverNum...

4

3 回答 3

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 都支持。

于 2012-09-19T11:13:54.000 回答
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
于 2012-09-19T11:14:41.157 回答
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
)
于 2012-09-19T11:32:19.593 回答