简体   繁体   English

SQL查询-在计数大于值的地方选择max

[英]SQL query - select max where a count greater than value

I've got two tables with the following structure: 我有两个具有以下结构的表:

Question table 问题表

id int, 
question text, 
answer text, 
level int

Progress table 进度表

qid int, 
attempts int, 
completed boolean (qid means question id)

Now my questions is how to construct a query that selects the max level where the count of correct questions is greater than let's say 30. 现在,我的问题是如何构建一个查询,以选择正确问题的数量大于30的最大级别。

I created this query, but it doesn't work and I don't know why. 我创建了此查询,但是它不起作用,我也不知道为什么。

SELECT MAX(Questions.level) 
FROM Questions, Progress 
WHERE Questions.id = Progress.qid AND Progress.completed = 1 
GROUP BY  Questions.id, Questions.level 
Having COUNT(*) >= 30

I would like to have it in one query as I suspect this is possible and probably the most 'optimized' way to query for it. 我想在一个查询中使用它,因为我怀疑这是可能的,并且可能是最“优化”的查询方式。 Thanks for the help! 谢谢您的帮助!

This sort of construct will work. 这种构造将起作用。 You can figure out the details. 您可以找出细节。

select max(something) maxvalue
from SomeTables
join (select id, count(*) records
from ATable
group by id) temp on ATable.id = temp.id
where records >= 30

Do it step by step rather than joining the two tables. 分步执行而不是将两个表联接在一起。 In an inner select find the questions (ie the question ids) that were answered 30 times correctly. 在内部选择中,找到正确回答了30次的问题(即问题ID)。 In an outer select find the corresponding levels and get the maximum value: 在外部选择中,找到相应的级别并获得最大值:

select max(level) 
from questions
where id in
(
  select qid
  from progress 
  where completed = 1
  group by qid
  having count(*) >= 30
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM