(Query)第一个正确解决方案之前的尝试次数



我有一个表解决方案,其中包含:id,user_id,problem_id correct,date,trys

其中correct可以是true或false

日期是解决方案保存的日期

trys是用户提交解决方案的次数

user_id  problem_id  tries correct
-------  ----------  ----- --------
1        1           1     true
1        2           1     false
1        2           2     false
1        2           3     false
1        3           1     false
1        3           2     false
1        3           3     true
1        3           4     false

我需要在第一个正确的解决方案之前获得用户的尝试次数,所以我试过这个:

SELECT problem_id, tries FROM solution
where user_id= and correct = true
group by problem_id order by date;

这给了我第一个正确解决方案之前的尝试次数,但仅限于至少一次正确的解决方案。

problem_id  tries 
----------  ----- 
1           1    
3           3    

我还需要查看尝试次数,即使用户从未有过正确的解决方案。如何将这两个结果结合起来?

problem_id  tries 
----------  ----- 
1           1
2           3    
3           3    

可能使用子查询(未测试):-

SELECT problem_id, IF(b.user_id IS NULL, 0, COUNT(*))
FROM solution a
LEFT OUTER JOIN
(
    SELECT user_id, problem_id, MIN(date) AS min_date
    FROM solution
    WHERE correct = true
    GROUP BY user_id, problem_id
) b
ON a.problem_id = b.problem_id
AND a.user_id = b.user_id
AND a.date < b.min_date
WHERE a.user_id = ?
GROUP BY problem_id

编辑-玩过测试数据后,我想我可能有一个解决方案。不确定是否有任何边缘情况,但它失败了:-

SELECT a.user_id, a.problem_id, SUM(IF(b.user_id IS NULL OR a.date <= b.min_date, 1, 0))
FROM solution a
LEFT OUTER JOIN 
(
    SELECT user_id, problem_id, MIN(date) AS min_date
    FROM solution
    WHERE correct = 'true'
    GROUP BY user_id, problem_id
) b
ON a.problem_id = b.problem_id
AND a.user_id = b.user_id
GROUP BY a.user_id, problem_id

这有一个子查询,用于查找用户问题的正确解决方案的最低日期,并将其与解决方案列表相关联。它执行1或0的和,如果没有正确的解决方案,或者如果有正确的解决解决方案,并且该正确解决方案的日期大于或等于该解决方案日期,则行计数为1。

SQL在这里为它摇旗呐喊:-

http://www.sqlfiddle.com/#!2/f48e11/1

如果你提到的查询得到了你想要的"正确"答案,要得到"不正确"的数字,只需将查询与自身的有效副本联合起来,将Correct=true调整为Correct=false谓词。

相关内容

最新更新