SELECT
  ae.id AS ID,
  ae.eventtime AS StartTimestamp,
  CONCAT(
    LPAD(FLOOR(TIMESTAMPDIFF(SECOND, ae.eventtime, NOW())/3600), 2, '0'), ':',
    LPAD(FLOOR((TIMESTAMPDIFF(SECOND, ae.eventtime, NOW())%3600)/60), 2, '0'), ':',
    LPAD(      (TIMESTAMPDIFF(SECOND, ae.eventtime, NOW())%60),      2, '0')
  ) AS Duration,
  CONCAT(REPLACE(ae.displaypath,'_','-'),' ', SUBSTRING_INDEX(ae.source,':/alm:',-1)) AS Description,
  CASE ae.priority
    WHEN 0 THEN 'Diagnostic' WHEN 1 THEN 'Low' WHEN 2 THEN 'Medium'
    WHEN 3 THEN 'High'       WHEN 4 THEN 'Critical' ELSE 'Unknown'
  END AS Priority,
  CONCAT(ae.displaypath,'.HMI.Alarm.', SUBSTRING_INDEX(aed.strValue,'/',-1)) AS Tag,
  SUBSTRING_INDEX(SUBSTRING_INDEX(aed.strValue,'/',2),'/',-1) AS Location,
  aed.strValue AS FullTag,
  ae.displaypath AS Device
FROM alarm_events ae
LEFT JOIN alarm_events clr
  ON clr.eventid = ae.eventid AND clr.eventtype = 1
LEFT JOIN alarm_event_data aed
  ON aed.id = ae.id AND aed.propname = 'myTag'
WHERE ae.eventtype = 0
  AND clr.eventid IS NULL
  AND ae.displaypath NOT LIKE '%System Startup%'
  AND ae.source      NOT LIKE '%System Startup%'
  AND (:priorityList = '' OR FIND_IN_SET(CAST(ae.priority AS CHAR), :priorityList) > 0)
ORDER BY ae.eventtime DESC;
