[英]Get records in Last 24 Hours having matching data and the maximum value
我有一張桌子下面的桌子。
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小時內收到的警報數量以及發送最新警報的通知版本。
我在結果中需要的列是
我嘗試了一些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在這里 。
您可以使用派生表的想法來獲取最新的ID並計算最近24小時的計數。
SELECT
COUNT(`notification_id`) AS AlertCount,
MAX(`notification_id`) AS MaxNotification
FROM
`notifications`
WHERE
`created_time` BETWEEN DATE_SUB(NOW(), INTERVAL 24 HOUR) AND NOW()
AND `not_type` = 'Alert';
然后,加入並進行過濾:
SELECT
NotificationTbl.source,
NotificationTbl.notification_reason,
NotificationTbl.notifier_version,
Last24HoursTbl.alert_count
FROM
`notifications` AS NotificationTbl
INNER JOIN
(
SELECT
COUNT(`notification_id`) AS alert_count,
MAX(`notification_id`) AS max_notification_id
FROM
`notifications`
WHERE
`created_time` BETWEEN DATE_SUB(NOW(), INTERVAL 24 HOUR) AND NOW()
AND `not_type` = 'Alert'
) AS Last24HoursTbl
ON NotificationTbl.notification_id = Last24HoursTbl.max_notification_id
;
結果(截至回答時間):
source | notification_reason | notifier_version | alert_count
------------------------------------------------------------
Europe | Some Reason 1 | NO_03 | 1
SQLFiddle: http ://sqlfiddle.com/#!9/14bb6a/14
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.