I need to fetch 12 questions from my table. I have a field called "bucket" which might have duplicate values. While fetching, I need only unique bucket values to be fetched and the number of rows has to be 12.
This is my query:
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;
Can anyone please tell me what am I doing wrong here? It sometimes doesn't return 12 rows. This happens whenever a same bucket value is found. I think, whenever distinct is applied that duplicate row's value is removed. Hence, when I do rn<=4 it is not able to find say, 3. Thus returning only 3 rows instead of 4.
So, I need to apply distinct on bucket first and then get row_numbers. How shall I do that?