如何找到表中包含最大值的记录?
虽然这个问题看起来很简单,但其实有点棘手。
考虑下表:
CREATE TABLE A (
id INT,
value FLOAT,
"date" DATETIME,
group VARCHAR(50)
);
我想获取包含按 列分组的最大
。 换句话说,类似于“每个组的最新值是多少?”什么查询将回答该问题?日期
的记录的 ID
和 值
组
我可以获得每个组及其最大日期:
SELECT group, MAX(date)
FROM A
GROUP BY group; -- I also need the "ID" and "value"`
但我希望获得具有最高日期的记录的“ID”和值。
在 A
和结果之间进行 JOIN
可能是答案,但无法知道 MAX(date)
引用的是哪条记录 (如果日期
重复)。
样本数据:
INSERT INTO A
VALUES
(1, 1.0, '2000-01-01', 'A'),
(2, 2.0, '2000-01-02', 'A'),
(3, 3.0, '2000-01-01', 'B'),
(4, 2.0, '2000-01-02', 'B'),
(5, 1.0, '2000-01-02', 'B')
;
Although this question looks simple, it is kind of tricky.
Consider the following table:
CREATE TABLE A (
id INT,
value FLOAT,
"date" DATETIME,
group VARCHAR(50)
);
I would like to obtain the ID
and value
of the records that contain the maximum date
grouped by the column group
. In other words, something like "what is the newest value for each group?" What query will answer that question?
I can get each group and its maximum date:
SELECT group, MAX(date)
FROM A
GROUP BY group; -- I also need the "ID" and "value"`
But I would like to have the "ID" and value of the record with the highest date.
Making a JOIN
between A
and the result could be the answer, but there is no way of knowing which record MAX(date)
refers to (in case the date
repeats).
Sample data:
INSERT INTO A
VALUES
(1, 1.0, '2000-01-01', 'A'),
(2, 2.0, '2000-01-02', 'A'),
(3, 3.0, '2000-01-01', 'B'),
(4, 2.0, '2000-01-02', 'B'),
(5, 1.0, '2000-01-02', 'B')
;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只要“日期”列对于每个组都是唯一的,我认为这样的方法可能会起作用:
As long as the Date column is unique for each group I think something like this might work:
您可以尝试使用子查询
You could try with a subquery
这正是分析函数的用途:
This is just what analytic functions were made for:
如果日期是唯一的,那么您已经有了答案。 如果日期不唯一,那么您需要一些其他唯一符。 如果没有自然密钥,您的 ID 就和任何 ID 一样好。 只需在其上输入 MAX(或 MIN,无论您喜欢哪个)即可:
If date is unique, then you already have your answer. If date is not unique, then you need some other uniqueifier. Absent a natural key, your ID is as good as any. Just put a MAX (or MIN, whichever you prefer) on it: