首页 > 解决方案 > 获取最近 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 小时内收到的警报数量以及发送最后警报的通知版本。

我在结果中需要的列是,

  1. 源 - 表中的不同实例
  2. notification_reason - 最后一次通知引发的事件,如果它在源的 24 小时之前
  3. notifier_version - 导致源的最后一个警报的 Notfier 版本
  4. alert_count - 源的过去 24 小时内的警报数。

我在这个 SQL Fiddle中尝试了一些东西。有人可以纠正我并给出解决方案

标签: mysqlsql

解决方案


我认为这可以满足您的要求:

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 在这里


推荐阅读