很抱歉我的描述不好,但我想知道最后一个吃了每个水果的人的最新日期。我不认为我正在将它分组,或者我完全错过了一些东西。有人可以帮我弄这个吗?提前谢谢。
T1
+--------+--------+--------+
| person | fruit | date |
+--------+--------+--------+
| Bob | apple | 1-1-13 |
| Bob | apple | 1-4-13 |
| Bob | apple | 1-6-13 |
| Bob | orange | 1-2-13 |
| John | apple | 1-3-13 |
| John | orange | 1-2-13 |
| John | orange | 1-4-13 |
| John | orange | 1-9-13 |
+--------+--------+--------+
Results I'm looking for
+--------+--------+--------+
| person | fruit | date |
+--------+--------+--------+
| Bob | apple | 1-6-13 |
| Bob | orange | 1-2-13 |
| John | apple | 1-3-13 |
| John | orange | 1-9-13 |
+--------+--------+--------+
我在阅读类似的帖子时尝试了什么。
SELECT * FROM T1
JOIN (
SELECT person,max(date) AS latest
FROM T1 GROUP BY person
) T2
ON T1.person = T2.person AND T1.date = T2.latest
Resulting in
+--------+--------+--------+
| person | fruit | date |
+--------+--------+--------+
| Bob | apple | 1-6-13 |
| John | orange | 1-9-13 |
+--------+--------+--------+
如何将水果柱分开?
答案 0 :(得分:2)
此处无需JOIN
。简单聚合GROUP BY
。
SELECT person, fruit, DATE_FORMAT(MAX(date), '%c-%e-%y') AS max_date
FROM T1
GROUP BY person, fruit
<强>结果强>
| PERSON | FRUIT | MAX_DATE | ------------------------------ | Bob | apple | 1-6-13 | | Bob | orange | 1-2-13 | | John | apple | 1-3-13 | | John | orange | 1-9-13 |