Mysql Join - 根据两个最大值过滤结果

时间:2015-06-23 13:48:51

标签: mysql

我有以下数据集:

+----+------------+------+-------+----------+
| id |    date    | week | time  |  price   |
+----+------------+------+-------+----------+
|  1 | 2015-05-01 |   24 | 13:25 | 1.251325 |
|  2 | 2015-05-01 |   24 | 14:25 | 1.251256 |
|  3 | 2015-05-02 |   24 | 15:25 | 1.251715 |
|  4 | 2015-05-02 |   24 | 16:25 | 1.251588 |
|  5 | 2015-05-10 |   25 | 17:25 | 1.251347 |
+----+------------+------+-------+----------+

我使用以下代码在每天结束时获得最新价格,从而提供完美的结果:

SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.date, MAX(tt.time) as 'maxtime'
FROM db1 tt
GROUP BY tt.date
) m
ON m.maxtime = t.time AND t.date = m.date;

但是,现在我还要查询每周的最新价格。因此,我需要在每周内查找最新日期,然后查找最长时间。我试过这样的事情,但这显然不是正确的语法:

SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.date, MAX(tt.time) as 'maxtime'
FROM db1 tt
GROUP BY tt.date
AND 
SELECT tt.week, MAX(tt.date) as 'maxdate'
FROM db1 tt
GROUP BY tt.week
) m
ON m.maxtime = t.time AND m.week = t.week AND m.maxdate = t.date;

问题是如何基于两个不同的" Group by"来链接这两个条件。我正在寻找的结果应该是这样的:

+----+------------+------+-------+----------+
| id |    date    | week | time  |  price   |
+----+------------+------+-------+----------+
|  4 | 2015-05-02 |   24 | 16:25 | 1.251588 |
|  5 | 2015-05-10 |   25 | 17:25 | 1.251347 |
+----+------------+------+-------+----------+

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

很奇怪您有日期和时间的单独列,但可能需要重复存储(每天11:00)或无日期的日期。否则你应该使用日期时间。

您要查找的是一周内的最新日期时间或时间戳。当你结合日期和时间时,你会得到这个。

SELECT t.id, t.date, t.time, t.balance
FROM db1 t JOIN
(SELECT tt.week, MAX(timestamp(tt.date,tt.time)) as 'maxtime'
FROM db1 tt
GROUP BY tt.week
) m
ON m.maxtime = timestamp(t.date,t.time) AND t.week = m.week;

答案 1 :(得分:2)

我建议您做什么,如果它不能将您的日期和时间对象合并到一个DATETIME列中,那么首先要研究TIMESTAMP()函数,该函数可用于转换两者列成一个日期时间对象,如下所示:

SELECT TIMESTAMP(dateColumn, timeColumn) AS fullDate
FROM myTable;

一旦你有了这个,你就可以编写一个查询来获取每周的最大日期时间,并加入到原始表中以获得所有这样的值:

SELECT m.*
FROM myTable m
JOIN(
  SELECT week, MAX(TIMESTAMP(dateColumn, timeColumn)) AS latestDate
  FROM myTable
  GROUP BY week) mt ON mt.week = m.week AND mt.latestDate = TIMESTAMP(m.datecolumn, m.timecolumn);

以下是SQL Fiddle示例。

答案 2 :(得分:1)

您可以将日期和时间连接成一个值,然后将max应用于此:

SELECT t.id, t.date, t.week, t.time, t.price
FROM db1 t 
JOIN (
  SELECT tt.week, MAX(concat(tt.date, ' ', tt.time)) as 'maxtime'
  FROM db1 tt
  GROUP BY tt.week
) m ON m.maxtime = concat(t.date, ' ', t.time) and t.week = m.week;

Sample SQL Fiddle