WITH counts AS (
  SELECT
    CAST(COALESCE(SUM(Fluid_Inbound_MCM03 = 1), 0) AS SIGNED) AS Fluid_Inbound_MCM03,
    CAST(COALESCE(SUM(Fluid_Inbound_MCM02 = 1), 0) AS SIGNED) AS Fluid_Inbound_MCM02,
    CAST(COALESCE(SUM(Bulk_Inbound        = 1), 0) AS SIGNED) AS Bulk_Inbound
  FROM jam_area
  WHERE t_stamp BETWEEN :starttime AND :endtime
),
totals AS (
  SELECT (Fluid_Inbound_MCM03 + Fluid_Inbound_MCM02 + Bulk_Inbound) AS Jam_Total
  FROM counts
),
labels AS (
  SELECT 'Fluid Inbound MCM03' AS Area UNION ALL
  SELECT 'Fluid Inbound MCM02' UNION ALL
  SELECT 'Bulk Inbound'
)
SELECT
  l.Area,
  CASE WHEN l.Area = 'Fluid Inbound MCM03' THEN c.Fluid_Inbound_MCM03 END AS `Fluid Inbound MCM03`,
  CASE WHEN l.Area = 'Fluid Inbound MCM02' THEN c.Fluid_Inbound_MCM02 END AS `Fluid Inbound MCM02`,
  CASE WHEN l.Area = 'Bulk Inbound'        THEN c.Bulk_Inbound        END AS `Bulk Inbound`,
  t.Jam_Total AS `Jam Count`
FROM labels l
CROSS JOIN counts c
CROSS JOIN totals t;
