我需要从我的表中取出 12 个问题。我有一个名为“bucket”的字段,它可能有重复的值。获取时,我只需要获取唯一的存储桶值,并且行数必须为 12。
这是我的查询:
select *
from (
select
DISTINCT ON (q.bucket) bucket,
row_number() over (partition by dl.value order by random()) as rn,
row_number() over (partition by dl.value, LOWER(qc.value) = LOWER('general') order by random()) as rnc,
dl.value, qc.value as question_category,
q.question_text, q.option_a, q.option_b, q.option_c, q.option_d,
q.correct_answer, q.image_link, q.question_type
from
questions_bank q
inner join
question_category qc on qc.id = q.question_category_id
inner join
sports_type st on st.id = q.sports_type_id
inner join
difficulty_level dl on dl.id = q.difficulty_level_id
where st.game_type = lower('cricket') and dl.value in ('E','M','H')
) s
where
(value = 'E' and rnc <= 3 and LOWER(question_category) != LOWER('general')) or
(value = 'E' and rnc <= 3 and LOWER(question_category) = LOWER('general')) or
value = 'M' and rn <= 4 or
value = 'H' and rn <= 2;
谁能告诉我我在这里做错了什么?它有时不会返回 12 行。只要找到相同的存储桶值,就会发生这种情况。我认为,每当应用 distinct 时,都会删除重复行的值。因此,当我执行 rn<=4 时,它无法找到 3。因此只返回 3 行而不是 4 行。
所以,我需要先在bucket上应用distinct,然后再获取row_numbers。我该怎么做?