SQL查询返回查询中的最高日期值

时间:2014-09-10 05:55:56

标签: mysql sql greatest-n-per-group

我试图运行查询来执行以下操作:
返回给定日期范围内表格中的所有最新条目 目前我正在使用此查询

SELECT id FROM schedule WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07'

从下面显示的日程表中返回记录1,2,3,4,5

日程表。

+----+------------+-------------+-----------------+------------+----------+
| id | eventdate  | resource_id |      text       |  added_on  | added_by |
+----+------------+-------------+-----------------+------------+----------+
|  1 | 2014-09-05 |           1 | Some old text   | 2014-08-01 | Sam      |
|  2 | 2014-09-05 |           1 | Some newer text | 2014-09-01 | Jordan   |
|  3 | 2014-09-06 |           1 | another day     | 2014-09-03 | Jordan   |
|  4 | 2014-09-05 |           1 | Most recent     | 2014-09-10 | Jordan   |
|  5 | 2014-09-07 |           2 | Other resource  | 2014-09-09 | Sam      |
+----+------------+-------------+-----------------+------------+----------+

我尝试仅返回指定日期范围内的唯一记录,其中应返回的唯一记录是added_on列中具有最高日期时间戳的记录。

在上面的示例中,我想仅返回记录3,4,5。记录1和2已被记录4取代。

**请注意:added_on列的类型为日期时间戳(yyyy-mm-dd HH:mm:ss)并且为了清晰起见而一直处于停止状态**

我不知道查询将返回的行数,决定记录唯一性的信息是eventdate, resource_id and added_on
即,每天每个资源只应返回一条记录,并且此记录应具有最高的added_on值

4 个答案:

答案 0 :(得分:2)

SELECT s1.* FROM schedule s1  
inner join (select max(id) as id1 from schedule WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07' group by eventdate,resource_id ) as s2 on s2.id1=s1.id 

它适用于你

答案 1 :(得分:1)

注意:

你说你通过三列eventdate,resource_id和added_on来确定每一天的唯一性......但是你只想要每天最大的added_on ...所以不要通过added_on分组... group by eventdate来获取每天的数据,按eventdate分组,resource_id按资源_id每天获取数据。

尝试获取唯一ID,然后按其过滤外部查询

SELECT * 
FROM schedule
WHERE ID IN
(   SELECT MAX(id) 
    FROM schedule 
    WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07' 
    GROUP BY eventdate, resource_id
)

DEMO1

或者如果您想使用最高的added_on,您可以采用相同的方式

SELECT * 
FROM schedule
WHERE added_on IN
(   SELECT MAX(added_on) 
    FROM schedule 
    WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07' 
    GROUP BY eventdate, resource_id
)

DEMO2

如果你想摆脱使用IN并使用JOIN,你可以在MAX()上添加JOIN来实现。

SELECT * 
FROM schedule s
JOIN 
(   SELECT MAX(added_on) as added_on 
    FROM schedule
    WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07' 
    GROUP BY eventdate, resource_id
) t ON t.added_on = s.added_on

DEMO3

答案 2 :(得分:1)

您需要获取eventdate,resource_id,added_on的每个唯一组合的最新记录,如下所示:

SELECT schedule.* 
FROM schedule JOIN (
   SELECT MAX(id) AS max_id 
   FROM schedule
   GROUP BY eventdate, resource_id, added_on
) t
ON t.max_id = schedule.id
WHERE eventdate BETWEEN '2014-09-01' AND '2014-09-07'

答案 3 :(得分:1)

我认为这将是您可以拥有的最简单的查询。如果您还有其他问题,请在此处发表评论。

 SELECT MAX(id) , eventdate, Max(added_on) FROM schedule GROUP BY eventdate.

这将返回

+----+------------+------------+
| id | eventdate  |  added_on  | 
+----+------------+------------+
|  3 | 2014-09-06 | 2014-09-03 | 
|  4 | 2014-09-05 | 2014-09-10 | 
|  5 | 2014-09-07 | 2014-09-09 | 
+----+------------+------------+