0

我在为以下问题编写 SQL 时遇到了很大的困难:

我在“答案”表中有以下数据库列

user_id integer,
question_id integer,
session_id text,
crated_date timestamp,
correct_answer boolean

现在我想要一个会话列表,并计算该会话中每个问题的正确和不正确的第一个答案。每个用户可能在一个会话期间多次回答相同的问题,我想知道有多少问题在他们第一次出现在会话中时被正确/不正确地回答。该列created_date确定答案的顺序。我试图获得的结果应该具有以下格式:

session_id text,
user_id integer,
questions_answered_correctly_first_time_in_session integer,
questions_answered_incorrectly_first_time_in_session integer,
questions_answered_correctly_after_first_time_in_session integer,
questions_answered_incorrectly_after_first_time_in_session integer

任何帮助,将不胜感激 :)

4

1 回答 1

1

我不是 100% 确定这会奏效,但你可以试一试:

请注意,这是一个即时构建的想法,我根本没有看过性能,可能有更好的方法。

with first_answers as (select
        session_id,
        question_id,
        min(created_date) as created_date,
        TRUE as first_answer
    from answers
    group by session_id, question_id)
select
    first.session_id,
    first.user_id,
    sum(case when coalesce(first_answer, FALSE) and correct_answer then 1 else 0 end),
    sum(case when coalesce(first_answer, FALSE) and not correct_answer then 1 else 0 end),
    sum(case when not coalesce(first_answer, FALSE) and correct_answer then 1 else 0 end),
    sum(case when not coalesce(first_answer, FALSE) and not correct_answer then 1 else 0 end)
from answers left join first_answers using (session_id, user_id, created_date)
group by session_id
于 2013-02-08T02:01:30.567 回答