我有下表(mTable)
id | sent | number
---------------------------------------
23 | 2017-03-02 00:00:00 | 0
23 | 2017-03-04 00:00:00 | 0
45 | 2017-03-15 00:00:00 | 1.8
45 | 2017-03-17 00:00:00 | 1.9
id: integer, not unique, no primary key
sent: timestamp
number: float
SQL语句:
SELECT DISTINCT `id`, number as mynum, MAX(`sent`) AS sentOn FROM `mTable` GROUP BY `id`
结果是:
id | mynum | sentOn
------------------------------------
23 | 0 | 2017-03-04 00:00:00
45 | 1.8 | 2017-03-17 00:00:00
预期结果将是:
id | mynum | sentOn
------------------------------------
23 | 0 | 2017-03-04 00:00:00
45 | 1.9 | 2017-03-17 00:00:00
在第二行,我希望是最新发送日期(2017-03-17 00:00:00)的mynum(1.9)。 而SQL-Query提供了第二个最新发送日期(2017-03-15 00:00:00)的mynum(1.8)。
任何提示,解决问题? 感谢的
答案 0 :(得分:1)
聚合是获取最新值的错误方法。这是一种更合适的方式:
select m.*
from mtable m
where m.sent = (select max(m2.sent) from mtable m2 where m.id = m2.id);
答案 1 :(得分:0)
如果您还需要maximum
的{{1}}值,则需要在mynum
上应用MAX
,例如:
mynum
答案 2 :(得分:0)
你正在使用Group By
条款哪个错了。在select
中使用聚合功能,然后使用Group By
..如下:
SELECT id, MAX(number) as mynum, MAX(sent) AS sentOn
FROM mTable
GROUP BY id
此链接有助于了解Group By Clause。