CREATE MATERIALIZED VIEW IF NOT EXISTS mv_answers
            ENGINE = MergeTree() ORDER BY event_time
            POPULATE AS
SELECT ctxquizid     AS quizid,
       ctxquestionid AS questionid,
       ctxsession    AS session,
       event_time
FROM default.statistics
WHERE (message IN ('InfoQuizOpen', 'InfoAnswer', 'InfoResult'))
  AND (event_level = 'info')
LIMIT 1 BY ctxquestionid, ctxsession;

CREATE VIEW IF NOT EXISTS view_last_answers AS
SELECT last_quesion,
    any(last_quiz)                     AS quiz,
       argMax(session, length(questions)) AS long_session
FROM default.view_respondent_paths
GROUP BY last_quesion;

CREATE VIEW IF NOT EXISTS view_pipelines_signs AS
SELECT target_quiz,
       questionid,
       long_sess
FROM (
         SELECT questionid,
             any(quiz)                AS target_quiz,
             any(long_session)        AS long_sess,
             groupArray(last_quesion) AS footsteps
         FROM default.view_last_answers
             INNER JOIN default.mv_answers ON long_session = session
         GROUP BY questionid
     )
WHERE length(footsteps) = 1;

CREATE VIEW IF NOT EXISTS view_respondent_paths AS
SELECT session,
       groupArray(questionid) AS questions,
       anyLast(questionid)    AS last_quesion,
       anyLast(quizid)        AS last_quiz
FROM default.mv_answers
GROUP BY session;

