[英]Query to get MAX value and corresponding date
桌子
+---------------------+-----------------------------+--------------+----------+
| timestamp | hostname | LICENSECOUNT | MAX_USED |
+---------------------+-----------------------------+--------------+----------+
| 2021-02-03 17:00:03 | server1 | 125 | 10 |
| 2021-02-03 17:00:06 | server2 | 415 | 50 |
| 2021-02-26 18:00:07 | server1 | 125 | 125 |
| 2021-02-26 18:00:09 | server2 | 415 | 415 |
| 2021-03-05 17:00:02 | server1 | 125 | 115 |
| 2021-03-05 17:00:04 | server2 | 415 | 315 |
我的查询- 获取过去 30 天内按服务器分组的许可证计数的最大值
select
timestamp, hostname, LICENSECOUNT, max(currentused) as MAX_USED
from
LICENSECHECKS
where
TIMESTAMP BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
group by hostname;
我的结果- 时间戳是数据集的开始(30 天前)
+---------------------+-----------------------------+--------------+----------+
| timestamp | hostname | LICENSECOUNT | MAX_USED |
+---------------------+-----------------------------+--------------+----------+
| 2021-02-03 17:00:03 | server1 | 125 | 125 |
| 2021-02-03 17:00:06 | server2 | 415 | 415 |
我想要的结果- 时间戳对应于日期
+---------------------+-----------------------------+--------------+----------+
| timestamp | hostname | LICENSECOUNT | MAX_USED |
+---------------------+-----------------------------+--------------+----------+
| 2021-02-26 18:00:07 | server1 | 125 | 125 |
| 2021-02-26 18:00:09 | server2 | 415 | 415 |
在子查询 select 语句中添加以下内容
ROW_NUMBER() OVER (PARTITION BY hostname ORDER BY currentuserid DESC) as RN
然后在外部查询 where 语句中提取 RN = 1 的行
您可以使用:
select lc.*
timestamp, hostname, LICENSECOUNT, max(currentused) as MAX_USED
from LICENSECHECKS
where lc.currentused = (select max(lc2.currentused)
from licensechecks lc2
where lc2.timestamp >= now() - interval 30 day and
lc2.hostname = lc.hostname
);
笔记:
timestamps
。now()
有一个时间组件。 我怀疑您可能想要curdate() - interval 29 day
类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.