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

时间:2013-02-08 01:03:00

标签: postgresql

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

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

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

现在我希望有一个会话列表,并为该会话中的每个问题计算正确和错误的FIRST答案。每个用户可以在一个会话期间多次回答相同的问题,我想知道在他们第一次出现在会话中时有多少问题被正确/不正确地回答。列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

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

我不是百分百肯定这会起作用,但你可以试一试:

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

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