sql - 按 T​​CP 地址划分的最大日期组

标签 sql greatest-n-per-group

我想要的:我遇到了每组最大 n 问题。我的组是一组 TCP 地址,n 是表行插入数据库的日期。

问题:我目前正在获取所有具有与我的 where 子句匹配的 tcp 地址的行,而不是每个 tcp 地址具有最大日期的行。

我正在尝试遵循此示例,但失败了:SQL Select only rows with Max Value on a Column

这是我的 table 的样子。

CREATE TABLE IF NOT EXISTS `xactions` (
  `id` int(15) NOT NULL AUTO_INCREMENT,
  `tcpAddress` varchar(40) NOT NULL,
   //a whole lot of other stuff in batween
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=150 ;

示例行是

ID | tcpAddress     | ...  | date
1  |  192.168.1.161 | ...  | 2012-09-12 14:19:39
2  |  192.168.1.162 | ...  | 2012-09-12 14:19:40
3  |  192.168.1.162 | ...  | 2012-09-12 14:19:41
4  |  192.168.1.162 | ...  | 2012-09-12 14:19:42

我尝试使用的 SQL 语句

select yt.id, yt.tcpAddress, yt.analog, yt.discrete, yt.counter, yt.date
from xactions yt
inner join(
    select id, tcpAddress, analog, discrete, counter, max(date) date
    from xactions
    WHERE tcpAddress='192.168.1.161' OR tcpAddress='192.168.1.162'
    group by date
) ss on yt.id = ss.id and yt.date= ss.date

最佳答案

您需要按 tcpAddress 进行分组,而不是按日期进行分组。

并通过 tcpAddress 加入,而不是 id。

select yt.id, yt.tcpAddress, yt.analog, yt.discrete, yt.counter, yt.date 
from xactions yt 
inner join ( 
  select tcpAddress, max(date) date 
  from xactions 
  where tcpAddress in ('192.168.1.161', '192.168.1.162')
  group by tcpAddress
 ) ss using (tcpAddress, date);

此外,您不需要在派生表中选择任何额外的列 - 只需选择 tcpAddress 和 max(date)。

关于sql - 按 T​​CP 地址划分的最大日期组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15420843/

相关文章:

sql-server-2008 - SQL Server : Greatest-N-per-group expanded

MySQL在多列中选择最大值

sql - 获取每个组的最后一行

MySQL 子查询 - 获取最新的时间戳记录并提取字段

mysql - 在 GROUP BY 中使用 LIMIT 来获得每组 N 个结果?

sql - 如何将直接值插入配置单元表?

php - MySql 反向 LIKE 子句

sql - 如何在SQL中拆分和显示单词的不同字母?

sql - 在分页期间获取SQL Server中记录总数的有效方法

mysql - 需要设计数据库方面的帮助