SELECT
  CONCAT(COALESCE(ae.displaypath,'Unknown'), ' - ',
         SUBSTRING_INDEX(COALESCE(ae.source,''), ':/alm:', -1))                   AS Description,
  SUBSTRING_INDEX(SUBSTRING_INDEX(COALESCE(aed.strValue,''), '/', 2), '/', -1)    AS Location,
  CONCAT(COALESCE(ae.displaypath,'Unknown'), '.HMI.',
         SUBSTRING_INDEX(COALESCE(aed.strValue,''),'/',-1))                       AS Tag,
  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,

  MIN(ae.eventtime)                                                               AS FirstTimestamp,
  MAX(ae.eventtime)                                                               AS LastTimestamp,

  -- total duration, formatted HH:MM:SS
  DATE_FORMAT(
    SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, ae.eventtime, COALESCE(clr.clear_time, NOW())))),
    '%H:%i:%s'
  )                                                                               AS Duration,

  COUNT(*)                                                                        AS Count,

  aed.strValue                                                                    AS FullTag,
  ae.displaypath                                                                  AS Device

FROM alarm_events ae
LEFT JOIN (
  -- get earliest clear per event
  SELECT eventid, MIN(eventtime) AS clear_time
  FROM alarm_events
  WHERE eventtype = 1
  GROUP BY eventid
) clr ON clr.eventid = ae.eventid
LEFT JOIN alarm_event_data aed
  ON aed.id = ae.id AND aed.propname = 'myTag'
WHERE ae.eventtype = 0
  AND COALESCE(ae.displaypath,'') NOT LIKE '%System Startup%'
  AND COALESCE(ae.source,'')      NOT LIKE '%System Startup%'
GROUP BY
  ae.source, ae.displaypath, aed.strValue
ORDER BY
  FirstTimestamp DESC, MIN(ae.id) DESC;
