mysql - 获取最近 24 小时内具有匹配数据和最大值的记录
问题描述
我有一张下面结构的桌子。
CREATE TABLE notifications (
`notification_id` int(11) NOT NULL AUTO_INCREMENT,
`source` varchar(50) NOT NULL,
`created_time` datetime NOT NULL,
`not_type` varchar(50) NOT NULL,
`not_content` longtext NOT NULL,
`notifier_version` varchar(45) DEFAULT NULL,
`notification_reason` varchar(245) DEFAULT NULL,
PRIMARY KEY (`notification_id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;
INSERT INTO `notifications` (`notification_id`,`source`,`created_time`,`not_type`,`not_content`,`notifier_version`,`notification_reason`) VALUES
(50,'Asia','2018-05-01 18:10:12','Alert','You are alerted for some Reason','NO_03','Some Reason 1'),
(51,'Asia','2018-04-29 14:10:12','Alert','You are alerted for some Reason','NO_02','Some Reason 8'),
(52,'Europe','2018-04-29 10:10:12','Warning','You are Warned for som Reason','NO_02',NULL),
(53,'Europe','2018-05-01 10:10:12','Warning','You are Warned for som Reason','NO_02',NULL),
(54,'Europe','2018-04-30 23:10:12','Alert','You are alerted for some Reason','NO_03','Some Reason 1');
我需要最新收到警报的来源列表、过去 24 小时内收到的警报数量以及发送最后警报的通知版本。
我在结果中需要的列是,
- 源 - 表中的不同实例
- notification_reason - 最后一次通知引发的事件,如果它在源的 24 小时之前
- notifier_version - 导致源的最后一个警报的 Notfier 版本
- alert_count - 源的过去 24 小时内的警报数。
我在这个 SQL Fiddle中尝试了一些东西。有人可以纠正我并给出解决方案
解决方案
我认为这可以满足您的要求:
select n.source,
max(case when na.max_ni = n.notification_id then notification_reason end) as last_alert_reason,
sum(n.not_type = 'Alert') as alert_count,
max(case when na.max_ni = n.notification_id then notifier_version end) as last_alert_version
from notifications n left join
(select n2.source, max(notification_id) as max_ni
from notifications n2
where n2.not_type = 'Alert'
group by n2.source
) na
on n.source = na.source
group by n.source;
SQL Fiddle 在这里。
推荐阅读
- java - 验证 vaadin 7 网格中的列值
- c - strcpy 与直接分配:溢出问题
- python - 如何在循环导入的情况下将 A 类的引用传递给 B 类,同时在 Pycharm 中保持类型提示和自动完成功能
- google-apps-script - 如果单元格文本有删除线,脚本将单元格颜色设置为无?
- sql-server - 如何在循环匹配条件下更新 Sql Server 表的记录?
- c++ - C++:reinterpret_cast 在这些场景中是最佳选择吗?
- java - 如何避免使用多个 throw 语句并仅使用一个带有所需错误消息的通用 throw 语句
- tcl - 如何使用 TCL 将 ipv4 转换为 ipv6 地址
- ios - 来自 Firebase 控制台 iOS 12.2 的推送通知不起作用
- react-native - 如何修复选项卡的样式(还有字体并使它们更薄)