0

I have a table named tbl_Question and a column named INT_MARK which has different marks for different questions. Like this:

VH_QUESTION     INT_MARK
-----------     --------
Q1              2
Q2              4

My question is: How to get a random set of 20 questions whose total sum of marks is 50?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Take a look at [this](http://stackoverflow.com/q/4329396/245679) – MD Sayem Ahmed Nov 20 '12 at 05:18
  • You'll need an algorithm, this is more a mathematical question, once you know the strategy, it will be to convert it to SQL query! – Alexandre Lavoie Nov 20 '12 at 05:19
  • A start: a) Pick 20 random questions. b) Do they add up to 50? c) If not, repeat. – tadman Nov 20 '12 at 05:20
  • SQL is about set-based solutions, while this problem, even though it's dealing with a data set, should probably be solved iteratively, and that generally isn't SQL's strongest suit. – Andriy M Nov 20 '12 at 12:45

4 Answers4

1
select VH_QUESTION, sum(INT_MARK) from tbl_Question
 group by VH_QUESTION
having sum(INT_MARK) > 50 
order by rand() limit 1
solaimuruganv
  • 27,177
  • 1
  • 18
  • 23
0

I think this question may help you - seems a very similar problem.

If that don't work, I'd try to divide the problem in two: first, you make a combinatory of your questions. Then, you filter them by it's sum of points.

I couldn't find, however, how to produce all combinations of the table. I don't know how difficult that would be.

Community
  • 1
  • 1
mgarciaisaia
  • 14,521
  • 8
  • 57
  • 81
0
select VH_QUESTION, sum(INT_MARK) from tbl_Question
group by VH_QUESTION
having sum(INT_MARK) >= 50 
order by rand() limit 20
AnandPhadke
  • 13,160
  • 5
  • 26
  • 33
0

Quick answer

SELECT * ,SUM(INT_MARK) as total_mark FROM tbl_Question  
GROUP BY VH_QUESTION
HAVING total_mark="50"
ORDER BY RAND()
LIMIT 5

it returns 0 line when no answers are possible but each time it finds one the questionsare random.

You could check the benchmark to see if you can have a faster query for large tables.

Jeffrey Nicholson Carré
  • 2,950
  • 1
  • 26
  • 44