-- NOTE(simkir): Example of using temp table to call crosstab, since the
-- crosstab cannot find a table made with a `WITH` type query
DROP TABLE IF EXISTS simulations;

CREATE TEMP TABLE simulations (
  group_name  text,
  sim_type    text,
  count       integer
);

INSERT INTO
  simulations (group_name, sim_type, count)
SELECT
  substring(session.distinct_id SIMILAR '%#"@%#"' ESCAPE '#') AS group,
  event_data.string_value as sim_type,
  COUNT(event_data.string_value)
FROM
  website_event
  JOIN session ON session.session_id = website_event.session_id
  LEFT OUTER JOIN event_data ON event_data.website_event_id = website_event.event_id
WHERE
  website_event.website_id = '16e7d807-4db5-45fd-92a9-27393445a153'
  AND website_event.event_type = 2
  AND website_event.event_name = 'mapster-submit-drifters'
  AND website_event.created_at BETWEEN '2025-11-10' AND '2025-11-18T23:59Z'
  AND session.distinct_id IS NOT NULL
  AND event_data.data_key = 'kind'
  -- AND event_data.created_at BETWEEN '2025-11-10' AND '2025-11-18'
GROUP BY
  substring(session.distinct_id SIMILAR '%#"@%#"' ESCAPE '#'),
  event_data.string_value;

SELECT
  *
FROM 
  crosstab_integer_5_cols(
    'SELECT * FROM simulations
     WHERE
       sim_type IN (''transport'', ''lice'', ''virus'', ''watercontact'', ''sedimentation'')
     ORDER BY 1, 2'
  )
