【问题标题】:Group by with maximum date按最大日期分组
【发布时间】:2013-12-27 14:40:27
【问题描述】:

我想从表格中选择数据,按此数据和日期值最大值分组。

在我的表中,我有 4 列 - id, message_id, client_id and date。列 id 是唯一的并且自动递增,而 message_id 和 client_id 具有重复值。日期几乎是唯一的。 我要select all records, group by message_id and client_id, that has date maximum

我的查询是 -

SELECT *,MAX(`date`) AS `maxdate` FROM `table_name` group by `message_id`,`client_id` order by `date` desc

但这并没有给出最大值的日期。 我正在获取第一个日期的分组记录。

请帮忙,告诉我正确的查询,我对mysql很陌生。

【问题讨论】:

  • 您的查询似乎是正确的。也许尝试提供一些示例数据。您还想检索对应于最大日期的 id 吗?如果是这样,您需要如下所述的自加入。

标签: mysql group-by


【解决方案1】:

试试这个查询 - 这就是我在 Oracle 中的做法:

select n1.id, n1.message_id, n1.client_id, n1.date
from shailjas_note n1
where n1.date = (select max(n2.date)
                  from shailjas_note n2
                  where n1.message_id = n2.message_id
                      and n1.client_id = n2.client_id)

【讨论】:

  • 感谢您的询问.. 它做到了我想要的。在我的查询中,我只需要添加这个 - ` order by maxdate desc`
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多