我发现很难绕过这个。例如,如果我有一个像这样的表:
table: cat
-------------------------------------------------------------
| id | currency |bank |created_at |
-------------------------------------------------------------
| 1 | a |1 |2015-05-12 19:30:55 |
| 2 | a |1 |2015-05-12 20:30:55 |
| 3 | b |2 |2015-05-12 19:30:55 |
| 4 | s |1 |2015-05-13 19:30:55 |
| 5 | b |2 |2015-05-13 23:30:55 |
| 6 | b |2 |2015-05-13 19:30:55 |
----------------------------------------------------
我的预期结果:
-------------------------------------------------------------
| id | currency |bank |created_at |
-------------------------------------------------------------
| 2 | a |1 |2015-05-12 20:30:55 |
| 3 | b |2 |2015-05-12 19:30:55 |
| 4 | s |1 |2015-05-13 19:30:55 |
| 5 | b |2 |2015-05-13 23:30:55 |
----------------------------------------------------
我的尝试:
SELECT p.id,p.currencyname, p.bank, date(p.created_at) as d, max(time(created_at)) as t, p.currencyname from cat as p GROUP by p.currencyname, d
答案 0 :(得分:1)
看起来您想要每个日历日的每种货币的最新(最大时间值)行。正如您专业地使用SQL一样,尊重您,花时间思考您的要求并准确描述它们至关重要。
以下是您获得所需结果的方法。
首先,您希望在每个日历日(created_at
)中找到每种货币的最新(MAX()
)行的DATE()
值。执行此操作的查询如下所示(http://sqlfiddle.com/#!9/a0e097/1/0):
SELECT DATE(created_at) day, currency, MAX(created_at) created_at
FROM cat
GROUP BY DATE(created_at), currency
然后将其用作子查询,并将其加入到您的表中。连接将从表中提取详细记录。你订购它是有道理的(http://sqlfiddle.com/#!9/a0e097/2/0)。
SELECT cat.id, cat.currency, cat.bank, cat.created_at
FROM cat
JOIN (
SELECT DATE(created_at) day, currency, MAX(created_at) created_at
FROM cat
GROUP BY DATE(created_at), currency
) a ON cat.currency = a.currency AND cat.created_at = a.created_at
ORDER BY cat.id