WITH base AS (
  SELECT
    w.created_at,
    s.distinct_id,
    substring(s.distinct_id SIMILAR '%#"@%#"' ESCAPE '#') AS "Group"
  FROM website_event AS w
  JOIN session AS s
    ON s.session_id = w.session_id
  WHERE
    w.website_id = '16e7d807-4db5-45fd-92a9-27393445a153'
    AND w.event_type = 1
    -- NOTE: This is only available in grafana
    -- AND $__timeFilter(w.created_at)
    AND w.created_at BETWEEN current_timestamp - '7 days'::interval and current_timestamp
    AND s.distinct_id IS NOT NULL
    -- AND substring(s.distinct_id SIMILAR '%#"@%#"' ESCAPE '#') IN ($groups)
),
unique_totals AS (
  SELECT
    "Group",
    COUNT(DISTINCT distinct_id) AS "Users in range"
  FROM base
  GROUP BY "Group"
),
unique_users AS (
  SELECT
    "Group",
    string_agg(DISTINCT distinct_id, ', ' ORDER BY distinct_id) AS "Users"
  FROM base
  GROUP BY "Group"
)
SELECT
  t."Group",
  t."Users in range" AS "Weekly users"
FROM unique_totals t
LEFT JOIN
  unique_users u USING ("Group")
WHERE
  t."Group" <> '@oceanbox.io'
ORDER BY
  "Users in range" DESC;
