SQL MAX()函数

时间:2013-12-07 16:52:06

标签: sql

假设我有一个表MATCHES(OPPONENT,DATE,GOALS_FOR,GOALS_AGAINST)

如果我想要一个返回GOALS_FOR大于2的最近匹配的SQL查询,那么我可以使用

SELECT *
FROM MATCHES
WHERE GOALS_FOR > 2
AND DATE = ( 
SELECT MAX(DATE)
FROM MATCHES
WHERE GOALS_FOR > 2)

如何在不重写/重新计算

的情况下完成此操作
MATCHES
WHERE GOALS_FOR > 2

两次?

4 个答案:

答案 0 :(得分:1)

只需按日期desc选择前1个订单,例如tsql

SELECT top 1 *
FROM MATCHES
WHERE GOALS_FOR > 2
ORDER BY DATE Desc

(使用rownum代表oracle,限制mysql,首先获取db2等)

答案 1 :(得分:0)

您可以简单地将其加入到每个DATE获取最新GOALS_FOR的子查询中。

SELECT  a.*
FROM    `matches` a
        INNER JOIN
        (
            SELECT  GOALS_FOR, MAX(DATE) Date
            FROM    `matches`
            WHERE   GOALS_FOR > 2
            GROUP   BY GOALS_FOR
        ) b ON  a.GOALS_FOR = b.GOALS_FOR
                AND a.Date = b.Date

答案 2 :(得分:0)

如果你的数据库支持WITH子句,你可以使用它:

WITH
matches_over_two_goals_for as (
SELECT *
FROM matches
WHERE goals_for > 2
)
SELECT MAX(date)
FROM matches_over_two_goals_for

答案 3 :(得分:0)

你有比赛的ID或钥匙吗?你需要GOALS_FOR>的原因2不止一次是因为在给定日期可能有多个匹配。因此,DATE比较可以提供与GOALS_FOR匹配的< 3。

如果您可以重写查询,请执行以下操作:

SELECT * FROM MATCHES WHERE MATCH_ID = ( SELECT MATCH_ID FROM MATCHES WHERE GOALS_FOR > 2 GROUP BY MATCH_ID HAVING MAX(DATE) = DATE )

你得到了照片