WITH counts AS (
  -- CTE 1: Calculates the raw counts for the three remaining jam types
  SELECT
    -- New metric: Merge_MCM01
    CAST(COALESCE(SUM(Merge_MCM01 = 1), 0) AS SIGNED) AS Merge_MCM01,
    -- New metric: Transport_MCM01
    CAST(COALESCE(SUM(Transport_MCM01 = 1), 0) AS SIGNED) AS Transport_MCM01,
    -- Kept metric: Sorter_MCM02
    CAST(COALESCE(SUM(Sorter_MCM02 = 1), 0) AS SIGNED) AS Sorter_MCM02
  FROM jam_area
  WHERE t_stamp BETWEEN :starttime AND :endtime
),
total AS (
  -- CTE 2: Calculates the sum of all three counts
  SELECT (Merge_MCM01 + Transport_MCM01 + Sorter_MCM02) AS Jam_Total
  FROM counts
),
labels AS (
  -- CTE 3: Defines the rows for the pivot based on the new metrics
  SELECT 'Merge_MCM01' AS Area UNION ALL
  SELECT 'Transport_MCM01' UNION ALL
  SELECT 'Sorter_MCM02'
)
SELECT
  l.Area,
  -- Only return Merge_MCM01 count when l.Area matches
  CASE WHEN l.Area = 'Merge_MCM01' THEN c.Merge_MCM01 END AS Merge_MCM01,
  -- Only return Transport_MCM01 count when l.Area matches
  CASE WHEN l.Area = 'Transport_MCM01' THEN c.Transport_MCM01 END AS Transport_MCM01,
  -- Only return Sorter_MCM02 count when l.Area matches
  CASE WHEN l.Area = 'Sorter_MCM02' THEN c.Sorter_MCM02 END AS Sorter_MCM02,
  t.Jam_Total AS `Total`
FROM labels l
CROSS JOIN counts c
CROSS JOIN total t;