选择范围内最大值的行

时间:2013-11-25 10:42:22

标签: php mysql sql

我有以下数据:

+----+---------+---------------------+-------+
| id | site_id |      datetime       | views |
+----+---------+---------------------+-------+
|  1 |       1 | 2013-11-01 23:59:59 |    12 |
|  2 |       1 | 2013-11-02 23:59:59 |    15 |
|  3 |       1 | 2013-11-03 23:59:59 |    18 |
|  4 |       1 | 2013-11-04 23:59:59 |    29 |
|  5 |       1 | 2013-11-05 23:59:59 |    38 |
|  6 |       1 | 2013-11-05 12:59:59 |    40 |
|  7 |       1 | 2013-11-06 23:59:59 |    45 |
|  8 |       1 | 2013-11-07 23:59:59 |    49 |
|  9 |       1 | 2013-11-08 23:59:59 |    52 |
| 10 |       2 | 2013-11-04 23:59:59 |    25 |
| 11 |       2 | 2013-11-05 21:59:59 |    42 |
| 12 |       2 | 2013-11-06 23:59:59 |    60 |
| 13 |       2 | 2013-11-07 23:59:59 |    75 |
| 14 |       2 | 2013-11-08 23:59:59 |    86 |
| 15 |       2 | 2013-11-09 23:59:59 |    90 |
| 16 |       2 | 2013-11-10 23:59:59 |    92 |
| 17 |       2 | 2013-11-11 23:42:59 |    98 |
+----+---------+---------------------+-------+

我会过一天,希望获得给定日期中时间最长的行,或者当天没有此站点的记录,这是过去最后一行。

e.g。 2013-11-01

+----+---------+---------------------+-------+
| id | site_id |      datetime       | views |
+----+---------+---------------------+-------+
|  1 |       1 | 2013-11-01 23:59:59 |    12 |
+----+---------+---------------------+-------+

代表2013-11-05

+----+---------+---------------------+-------+
| id | site_id |      datetime       | views |
+----+---------+---------------------+-------+
|  5 |       1 | 2013-11-05 23:59:59 |    38 |
| 11 |       2 | 2013-11-05 21:59:59 |    42 |
+----+---------+---------------------+-------+

2013-11-10

+----+---------+---------------------+-------+
| id | site_id |      datetime       | views |
+----+---------+---------------------+-------+
|  9 |       1 | 2013-11-08 23:59:59 |    52 |
| 16 |       2 | 2013-11-10 23:59:59 |    92 |
+----+---------+---------------------+-------+

提前致谢。

4 个答案:

答案 0 :(得分:5)

你可以试试这个:

SELECT a.id,a.site_id,b.maxDate,a.views
FROM table1 a
INNER JOIN (
    SELECT  site_id ,MAX(datetime) as maxDate
    FROM table1
    WHERE datetime < DATEYOUWANTTOSEE + INTERVAL 1 DAY
    GROUP BY site_id
) b ON a.site_id = b.site_id AND a.datetime = b.maxDate 

内部查询将为您获取每个site_id的MAX(日期时间)。然后你将它与你的表一起加入以获取其余的信息。

sqlfiddle demo

答案 1 :(得分:-1)

SELECT * FROM <tablename> WHERE datetime = <datetime> ORDER BY datetime DESC LIMIT 2

答案 2 :(得分:-2)

我相信这应该有效:

SELECT SUBSTRING(`datetime`, 1, 10) AS date, MAX(`views`)
FROM table
GROUP BY SUBSTRING(`datetime`, 1, 10)

如果您还需要id / site_id,请将其写在帖子中,因为不清楚

SQLFiddle向您展示结果: http://sqlfiddle.com/#!2/e0ccb3/1

答案 3 :(得分:-2)

您的数据和示例实际上并不匹配,也不是描述,但您可能正在寻找的是:

Select top 1 * 
  from table
 where date(datetime) <= date(@PARAMETER)

按日期时间desc排序