Postgresql:选择分组依据中的第一行(带扭曲)

Postgresql:选择分组依据中的第一行(带扭曲),postgresql,Postgresql,我在为以下问题编写SQL时遇到了很大困难: 我在“答案”表中有以下数据库列 现在我想要一份会议列表,并计算该会议中每个问题的正确答案和错误答案。每个用户在一次会话中可能会多次回答同一个问题,我想知道在会话中第一次出现的问题中,有多少个得到了正确/不正确的回答。“创建日期”列决定了答案的顺序。我试图获得的结果应具有以下格式: session_id text, user_id integer, questions_answered_correctly_first_time_in_session in

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

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

现在我想要一份会议列表,并计算该会议中每个问题的正确答案和错误答案。每个用户在一次会话中可能会多次回答同一个问题,我想知道在会话中第一次出现的问题中,有多少个得到了正确/不正确的回答。“创建日期”列决定了答案的顺序。我试图获得的结果应具有以下格式:

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

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

我不能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
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